text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Best way to subset a pandas dataframe Hey I'm new to Pandas and I just came across df.query().
Why people would use df.query() when you can directly filter your Dataframes using brackets notation ? The official pandas tutorial also seems to prefer the latter approach.
With brackets notation :
df[df['age'] <= 21]
With pandas query method :
df.query('age <= 21')
Besides some of the stylistic or flexibility differences that have been mentioned, is one canonically preferred - namely for performance of operations on large dataframes?
A: Some other interesting usages in the documentation.
Reuseable
A use case for query() is when you have a collection of DataFrame
objects that have a subset of column names (or index levels/names) in
common. You can pass the same query to both frames without having to
specify which frame you’re interested in querying -- (Source)
Example:
dfA = pd.DataFrame([[1,2,3], [4,5,6]], columns=["X", "Y", "Z"])
dfB = pd.DataFrame([[1,3,3], [4,1,6]], columns=["X", "Y", "Z"])
q = "(X > 3) & (Y < 10)"
print(dfA.query(q))
print(dfB.query(q))
X Y Z
1 4 5 6
X Y Z
1 4 1 6
More flexible syntax
df.query('a < b and b < c') # understand a bit more English
Support in operator and not in (alternative to isin)
df.query('a in [3, 4, 5]') # select rows whose value of column a is in [2, 3, 4]
Special usage of == and != (similar to in/not in)
df.query('a == [1, 3, 5]') # select whose value of column a is in [1, 3, 5]
# equivalent to df.query('a in [1, 3, 5]')
A: Consider the following sample DF:
In [307]: df
Out[307]:
sex age name
0 M 40 Max
1 F 35 Anna
2 M 29 Joe
3 F 18 Maria
4 F 23 Natalie
There are quite a few good reasons to prefer .query() method.
*
*it might be much shorter and cleaner compared to boolean indexing:
In [308]: df.query("20 <= age <= 30 and sex=='F'")
Out[308]:
sex age name
4 F 23 Natalie
In [309]: df[(df['age']>=20) & (df['age']<=30) & (df['sex']=='F')]
Out[309]:
sex age name
4 F 23 Natalie
*you can prepare conditions (queries) programmatically:
In [315]: conditions = {'name':'Joe', 'sex':'M'}
In [316]: q = ' and '.join(['{}=="{}"'.format(k,v) for k,v in conditions.items()])
In [317]: q
Out[317]: 'name=="Joe" and sex=="M"'
In [318]: df.query(q)
Out[318]:
sex age name
2 M 29 Joe
PS there are also some disadvantages:
*
*we can't use .query() method for columns containing spaces or columns that consist only from digits
*not all functions can be applied or in some cases we have to use engine='python' instead of default engine='numexpr' (which is faster)
NOTE: Jeff (one of the main Pandas contributors and a member of Pandas core team) once said:
Note that in reality .query is just a nice-to-have interface, in fact
it has very specific guarantees, meaning its meant to parse like a
query language, and not a fully general interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48370708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How to get href Text using CSS selectors I have the following HTML below from Wikipedia main page at https://www.wikipedia.org/. I'm trying to get the href text
//en.wikipedia.org/
<div class="central-featured-lang lang1" lang="en">
<a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box">
<strong>English</strong><br>
<em>The Free Encyclopedia</em><br>
<small>5 077 000+ articles</small>
</a>
</div>
I've tried this $$('.central-featured-lang.lang1 a[href$=".org/"]') but I still get the whole output, not just the href text.
[<a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box">…</a><strong>English</strong><br><em>The Free Encyclopedia</em><br><small>5 077 000+ articles</small></a>]
Any advice is much appreciated.
A: In Javascript you can use document.querySelector along with href attribute, like this:
var url = document.querySelector('.central-featured-lang.lang1 a[href$=".org/"]').href;
alert(url);
<div class="central-featured-lang lang1" lang="en">
<a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box">
<strong>English</strong>
<br>
<em>The Free Encyclopedia</em>
<br>
<small>5 077 000+ articles</small>
</a>
</div>
A: Use the .attr() Method:
$('.central-featured-lang.lang1 a[href$=".org/"]').attr("href")
var url = $('.central-featured-lang.lang1 a[href$=".org/"]').attr("href");
alert( url );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="central-featured-lang lang1" lang="en">
<a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box">
<strong>English</strong><br>
<em>The Free Encyclopedia</em><br>
<small>5 077 000+ articles</small>
</a>
</div>
A: Use DOM Element getAttribute() Method
getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned
will either be null or "" (the empty string); see Notes for details.
var element = document.querySelector('a.link-box'),
link = element.getAttribute('href');
alert(link)
<div class="central-featured-lang lang1" lang="en">
<a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box">
<strong>English</strong>
<br>
<em>The Free Encyclopedia</em>
<br>
<small>5 077 000+ articles</small>
</a>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36928172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Spring Boot creating multiple (functioning) webmvc applications using auto configuration Updated
My question is how do I initialise an isolated spring webmvc web-app in spring boot. The isolated Web application should:
*
*Should not initialise itself in the application class. We want to do these in a starter pom via auto configuration. We have multiple such web-apps and we need the flexibility of auto configuration.
*Have the ability to customise itself using interfaces like:
WebSecurityConfigurer (we have multiple web-apps, each does
security in its own way) and EmbeddedServletContainerCustomizer (to
set the context path of the servlet).
*We need to isolate beans specific to certain web-apps and do not want them to enter the parent context.
Progress
The configuration class below is listed in my META-INF/spring.factories.
The following strategy does not lead to a functioning web-mvc servlet. The context path is not set and neither is the security customised. My hunch is that I need to include certain webmvc beans that process the context and auto configure based on what beans are present -- similar to how I got boot based property placeholder configuration working by including PropertySourcesPlaceholderConfigurer.class.
@Configuration
@AutoConfigureAfter(DaoServicesConfiguration.class)
public class MyServletConfiguration {
@Autowired
ApplicationContext parentApplicationContext;
@Bean
public ServletRegistrationBean myApi() {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.setParent(parentApplicationContext);
applicationContext.register(PropertySourcesPlaceholderConfigurer.class);
// a few more classes registered. These classes cannot be added to
// the parent application context.
// includes implementations of
// WebSecurityConfigurerAdapter
// EmbeddedServletContainerCustomizer
applicationContext.scan(
// a few packages
);
DispatcherServlet ds = new DispatcherServlet();
ds.setApplicationContext(applicationContext);
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(ds, true, "/my_api/*");
servletRegistrationBean.setName("my_api");
servletRegistrationBean.setLoadOnStartup(1);
return servletRegistrationBean;
}
}
A: We had the similar issue using Boot (create a multi-servlets app with parent context) and we solved it in the following way:
1.Create your parent Spring config, which will consist all parent's beans which you want to share. Something like this:
@EnableAutoConfiguration(
exclude = {
//use this section if your want to exclude some autoconfigs (from Boot) for example MongoDB if you already have your own
}
)
@Import(ParentConfig.class)//You can use here many clasess from you parent context
@PropertySource({"classpath:/properties/application.properties"})
@EnableDiscoveryClient
public class BootConfiguration {
}
2.Create type which will determine the type of your specific app module (for example ou case is REST or SOAP). Also here you can specify your required context path or another app specific data (I will show bellow how it will be used):
public final class AppModule {
private AppType type;
private String name;
private String contextPath;
private String rootPath;
private Class<?> configurationClass;
public AppModule() {
}
public AppModule(AppType type, String name, String contextPath, Class<?> configurationClass) {
this.type = type;
this.name = name;
this.contextPath = contextPath;
this.configurationClass = configurationClass;
}
public AppType getType() {
return type;
}
public void setType(AppType type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRootPath() {
return rootPath;
}
public AppModule withRootPath(String rootPath) {
this.rootPath = rootPath;
return this;
}
public String getContextPath() {
return contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public Class<?> getConfigurationClass() {
return configurationClass;
}
public void setConfigurationClass(Class<?> configurationClass) {
this.configurationClass = configurationClass;
}
public enum AppType {
REST,
SOAP
}
}
3.Create Boot app initializer for your whole app:
public class BootAppContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private List<AppModule> modules = new ArrayList<>();
BootAppContextInitializer(List<AppModule> modules) {
this.modules = modules;
}
@Override
public void initialize(ConfigurableApplicationContext ctx) {
for (ServletRegistrationBean bean : servletRegs(ctx)) {
ctx.getBeanFactory()
.registerSingleton(bean.getServletName() + "Bean", bean);
}
}
private List<ServletRegistrationBean> servletRegs(ApplicationContext parentContext) {
List<ServletRegistrationBean> beans = new ArrayList<>();
for (AppModule module: modules) {
ServletRegistrationBean regBean;
switch (module.getType()) {
case REST:
regBean = createRestServlet(parentContext, module);
break;
case SOAP:
regBean = createSoapServlet(parentContext, module);
break;
default:
throw new RuntimeException("Not supported AppType");
}
beans.add(regBean);
}
return beans;
}
private ServletRegistrationBean createRestServlet(ApplicationContext parentContext, AppModule module) {
WebApplicationContext ctx = createChildContext(parentContext, module.getName(), module.getConfigurationClass());
//Create and init MessageDispatcherServlet for REST
//Also here you can init app specific data from AppModule, for example,
//you can specify context path in the follwing way
//servletRegistrationBean.addUrlMappings(module.getContextPath() + module.getRootPath());
}
private ServletRegistrationBean createSoapServlet(ApplicationContext parentContext, AppModule module) {
WebApplicationContext ctx = createChildContext(parentContext, module.getName(), module.getConfigurationClass());
//Create and init MessageDispatcherServlet for SOAP
//Also here you can init app specific data from AppModule, for example,
//you can specify context path in the follwing way
//servletRegistrationBean.addUrlMappings(module.getContextPath() + module.getRootPath());
}
private WebApplicationContext createChildContext(ApplicationContext parentContext, String name,
Class<?> configuration) {
AnnotationConfigEmbeddedWebApplicationContext ctx = new AnnotationConfigEmbeddedWebApplicationContext();
ctx.setDisplayName(name + "Context");
ctx.setParent(parentContext);
ctx.register(configuration);
Properties source = new Properties();
source.setProperty("APP_SERVLET_NAME", name);
PropertiesPropertySource ps = new PropertiesPropertySource("MC_ENV_PROPS", source);
ctx.getEnvironment()
.getPropertySources()
.addLast(ps);
return ctx;
}
}
4.Create abstract config classes which will contain child-specific beans and everything that you can not or don't want share via parent context. Here you can specify all required interfaces such as WebSecurityConfigurer or EmbeddedServletContainerCustomizer for your particular app module:
/*Example for REST app*/
@EnableWebMvc
@ComponentScan(basePackages = {
"com.company.package1",
"com.company.web.rest"})
@Import(SomeCommonButChildSpecificConfiguration.class)
public abstract class RestAppConfiguration extends WebMvcConfigurationSupport {
//Some custom logic for your all REST apps
@Autowired
private LogRawRequestInterceptor logRawRequestInterceptor;
@Autowired
private LogInterceptor logInterceptor;
@Autowired
private ErrorRegister errorRegister;
@Autowired
private Sender sender;
@PostConstruct
public void setup() {
errorRegister.setSender(sender);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(logRawRequestInterceptor);
registry.addInterceptor(scopeInterceptor);
}
@Override
public void setServletContext(ServletContext servletContext) {
super.setServletContext(servletContext);
}
}
/*Example for SOAP app*/
@EnableWs
@ComponentScan(basePackages = {"com.company.web.soap"})
@Import(SomeCommonButChildSpecificConfiguration.class)
public abstract class SoapAppConfiguration implements ApplicationContextAware {
//Some custom logic for your all SOAP apps
private boolean logGateWay = false;
protected ApplicationContext applicationContext;
@Autowired
private Sender sender;
@Autowired
private ErrorRegister errorRegister;
@Autowired
protected WsActivityIdInterceptor activityIdInterceptor;
@Autowired
protected WsAuthenticationInterceptor authenticationInterceptor;
@PostConstruct
public void setup() {
errorRegister.setSender(sender);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* Setup preconditions e.g. interceptor deactivation
*/
protected void setupPrecondition() {
}
public boolean isLogGateWay() {
return logGateWay;
}
public void setLogGateWay(boolean logGateWay) {
this.logGateWay = logGateWay;
}
public abstract Wsdl11Definition defaultWsdl11Definition();
}
5.Create entry point class which will compile whole our app:
public final class Entrypoint {
public static void start(String applicationName, String[] args, AppModule... modules) {
System.setProperty("spring.application.name", applicationName);
build(new SpringApplicationBuilder(), modules).run(args);
}
private static SpringApplicationBuilder build(SpringApplicationBuilder builder, AppModule[] modules) {
return builder
.initializers(
new LoggingContextInitializer(),
new BootAppContextInitializer(Arrays.asList(modules))
)
.sources(BootConfiguration.class)
.web(true)
.bannerMode(Banner.Mode.OFF)
.logStartupInfo(true);
}
}
Now everything is ready to rocket our super multi-app boot in two steps:
1.Init your child apps, for example, REST and SOAP:
//REST module
@ComponentScan(basePackages = {"com.module1.package.*"})
public class Module1Config extends RestAppConfiguration {
//here you can specify all your child's Beans and etc
}
//SOAP module
@ComponentScan(
basePackages = {"com.module2.package.*"})
public class Module2Configuration extends SoapAppConfiguration {
@Override
@Bean(name = "service")
public Wsdl11Definition defaultWsdl11Definition() {
ClassPathResource wsdlRes = new ClassPathResource("wsdl/Your_WSDL.wsdl");
return new SimpleWsdl11Definition(wsdlRes);
}
@Override
protected void setupPrecondition() {
super.setupPrecondition();
setLogGateWay(true);
activityIdInterceptor.setEnabled(true);
}
}
2.Prepare entry point and run as Boot app:
public class App {
public static void main(String[] args) throws Exception {
Entrypoint.start("module1",args,
new AppModule(AppModule.AppType.REST, "module1", "/module1/*", Module1Configuration.class),
new AppModule(AppModule.AppType.SOAP, "module2", "module2", Module2Configuration.class)
);
}
}
enjoy ^_^
Useful links:
*
*https://dzone.com/articles/what-servlet-container
*Spring: Why "root" application context and "servlet" application context are created by different parties?
*Role/Purpose of ContextLoaderListener in Spring?
A: This could be one way of doing this (it's in our production code). We point to XML config, so maybe instead of dispatcherServlet.setContextConfigLocation() you could use dispatcherServlet.setContextClass()
@Configuration
public class JettyConfiguration {
@Autowired
private ApplicationContext applicationContext;
@Bean
public ServletHolder dispatcherServlet() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MvcConfiguration.class);//CUSTOM MVC @Configuration
DispatcherServlet servlet = new DispatcherServlet(ctx);
ServletHolder holder = new ServletHolder("dispatcher-servlet", servlet);
holder.setInitOrder(1);
return holder;
}
@Bean
public ServletContextHandler servletContext() throws IOException {
ServletContextHandler handler =
new ServletContextHandler(ServletContextHandler.SESSIONS);
AnnotationConfigWebApplicationContext rootWebApplicationContext =
new AnnotationConfigWebApplicationContext();
rootWebApplicationContext.setParent(applicationContext);
rootWebApplicationContext.refresh();
rootWebApplicationContext.getEnvironment().setActiveProfiles(applicationContext.getEnvironment().getActiveProfiles());
handler.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
rootWebApplicationContext);
handler.setContextPath("/my-root");
handler.setResourceBase(new ClassPathResource("webapp").getURI().toString());
handler.addServlet(AdminServlet.class, "/metrics/*");//DROPWIZARD
handler.addServlet(dispatcherServlet(), "/");
/*Web context 1*/
DispatcherServlet webMvcDispatcherServlet1 = new DispatcherServlet();
webMvcDispatcherServlet1.setContextConfigLocation("classpath*:/META-INF/spring/webmvc-config1.xml");
webMvcDispatcherServlet1.setDetectAllHandlerAdapters(true);
webMvcDispatcherServlet1.setDetectAllHandlerMappings(true);
webMvcDispatcherServlet1.setDetectAllViewResolvers(true);
webMvcDispatcherServlet1.setEnvironment(applicationContext.getEnvironment());
handler.addServlet(new ServletHolder("webMvcDispatcherServlet1",webMvcDispatcherServlet1), "/web1/*");
/*Web context 2*/
DispatcherServlet webMvcDispatcherServlet2 = new DispatcherServlet();
webMvcDispatcherServlet2.setContextConfigLocation("classpath*:/META-INF/spring/web-yp-config.xml");
webMvcDispatcherServlet2.setDetectAllHandlerAdapters(true);
webMvcDispatcherServlet2.setDetectAllHandlerMappings(true);
webMvcDispatcherServlet2.setDetectAllViewResolvers(false);
webMvcDispatcherServlet2.setEnvironment(applicationContext.getEnvironment());
handler.addServlet(new ServletHolder("webMvcDispatcherServlet2",webMvcDispatcherServlet2), "/web2/*");
/* Web Serices context 1 */
MessageDispatcherServlet wsDispatcherServlet1 = new MessageDispatcherServlet();
wsDispatcherServlet1.setContextConfigLocation("classpath*:/META-INF/spring/ws-config1.xml");
wsDispatcherServlet1.setEnvironment(applicationContext.getEnvironment());
handler.addServlet(new ServletHolder("wsDispatcherServlet1", wsDispatcherServlet1), "/ws1/*");
/* Web Serices context 2 */
MessageDispatcherServlet wsDispatcherServlet2 = new MessageDispatcherServlet();
wsDispatcherServlet2.setContextConfigLocation("classpath*:/META-INF/spring/ws-siteconnect-config.xml");
wsDispatcherServlet2.setEnvironment(applicationContext.getEnvironment());
handler.addServlet(new ServletHolder("wsDispatcherServlet2", wsDispatcherServlet2), "/ws2/*");
/*Spring Security filter*/
handler.addFilter(new FilterHolder(
new DelegatingFilterProxy("springSecurityFilterChain")), "/*",
null);
return handler;
}
@Bean
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter bean = new CharacterEncodingFilter();
bean.setEncoding("UTF-8");
bean.setForceEncoding(true);
return bean;
}
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
HiddenHttpMethodFilter filter = new HiddenHttpMethodFilter();
return filter;
}
/**
* Jetty Server bean.
* <p/>
* Instantiate the Jetty server.
*/
@Bean(initMethod = "start", destroyMethod = "stop")
public Server jettyServer() throws IOException {
/* Create the server. */
Server server = new Server();
/* Create a basic connector. */
ServerConnector httpConnector = new ServerConnector(server);
httpConnector.setPort(9083);
server.addConnector(httpConnector);
server.setHandler(servletContext());
return server;
}
}
A: Unfortunately I couldn't find a way to use auto configuration for multiple servlets.
However, you can use the ServletRegistrationBean to register multiple servlets for your application. I would recommend you to use the AnnotationConfigWebApplicationContext to initiate the context because this way you can use the default Spring configuration tools (not the spring boot one) to configure your servlets. With this type of context you just have to register a configuration class.
@Bean
public ServletRegistrationBean servletRegistration() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(YourConfig.class);
DispatcherServlet servlet = new DispatcherServlet();
servlet.setApplicationContext(context);
ServletRegistrationBean registration = new ServletRegistrationBean(servlet, "/servletX");
registration.setLoadOnStartup(1);
registration.setName("servlet-X");
return registration;
}
If you want to handle multipart requests you should set the multipart configuration for the registration bean. This configuration can be autowired for the registration and will be resolved from the parent context.
public ServletRegistrationBean servletRegistration(MultipartConfigElement mutlipart) ...
registration.setMultipartConfig(mutlipartConfig);
I've created a little github example project which you can reach here.
Note that I set up the servlet configs by Java package but you can define custom annotations for this purpose too.
A: I manage to create an independant jar that makes tracking on my webapp and it is started depending on the value of a property in a spring.factories file in resources/META-INF in the main app:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=my package.tracking.TrackerConfig
Maybe, you could try to have independant war, started with this mechanism and then inject values in the properties files with maven mechanism/plugin (Just a theory, never tried, but based on several projects I worked on)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35095326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: Can't get JSON from nominatim url (openstreetmap) I cannot get the result from the URL JSON response of reverse geocoding.
I'm also getting the error:
"W/System.err: org.json.JSONException: End of input at character 0 of "
Here is the url https://nominatim.openstreetmap.org/reverse?format=geojson&lat=14.6458&lon=121.0949
HttpDataHandler.java
public String GetHTTPData(String requestUrl)
{
URL url;
String response = "";
try{
url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setDoOutput(true);
int responseCode = conn.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while((line = br.readLine()) != null)
response+=line;
}
else
response = "";
MainActivity
@Override
protected String doInBackground(String... strings) {
try{
double lat = Double.parseDouble(strings[0].split(",")[0]);
double lng = Double.parseDouble(strings[0].split(",")[1]);
String response;
HttpDataHandler http = new HttpDataHandler();
//String url = String.format("http://open.mapquestapi.com/geocoding/v1/reverse?key=2KtQuwfGGdfHxj6ybdgqcC7uFHrgVoJy&location=%.4f,%.4f",lat,lng);
String url = String.format("https://nominatim.openstreetmap.org/reverse?format=json&lat=%.4f&lon=%.4f",lat,lng);
response = http.GetHTTPData(url);
Log.d("testpandebug,doinbg", response);
Log.d("testpandebug,doinbg", url);
return response;
}
catch (Exception ex)
{
}
return null;
}
I'm using logs to get the response from the url yet. Upon using the other geocoder URL (commented string URL), it returns a response, however, using the nominatim doesnt return a response. I want to use the nominatim as it returns a more accurate reverse geocode.
A: If it doesn't return a valid body then take a look at the HTTP response header. I guess you are violating Nominatim's usage policy. Do you provide a valid HTTP user agent?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55105770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Doctrine: bidirectional OneToOne relationship, both entities being deleted Hey guys so I have 2 entities with a bidirectional OneToOne relationship:
Sale.php
/**
* @var TransportInvoice
*
* @ORM\OneToOne(targetEntity="WKDA\Common\Entity\Car\TransportInvoice\TransportInvoice", mappedBy="sale")
* @ORM\JoinColumn(name="transport_invoice", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*/
protected $transportInvoice;
TransportInvoice.php
/**
* @var Sale
* @ORM\OneToOne(targetEntity="WKDA\Common\Entity\Car\Sale", inversedBy="transportInvoice", cascade={"persist"}, orphanRemoval=true)
* @ORM\JoinColumn(name="sale", referencedColumnName="id", nullable=false)
*/
protected $sale;
In my controller, to delete a transport invoice from the sale, the following is done:
$transportInvoice = $car->getSale()->getTransportInvoice();
$em = $this->getEntityManager();
$em->remove($transportInvoice);
$em->flush();
This deletes the TransportInvoice, but it deletes the Sale object as well. I don't want the Sale object to be deleted, I just want the TransportInvoice parameter within sale to be null. What am I not understanding?
If this is not clear let me know, thanks for your help!
A: I think that the problem is the relation design. In your example Sale is the main entity, so the transport_invoice reference is not needed. The "sale" reference in TransportInvoice.php is all that doctrine need, so edit Sale as follow an try again.
/**
* @var TransportInvoice
*
* @ORM\OneToOne(targetEntity="WKDA\Common\Entity\Car\TransportInvoice\TransportInvoice", mappedBy="sale")
*/
protected $transportInvoice;
I hope it help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34438338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Generating a DataFrame from a list of rows line by line I have a highly irregular text file that I am trying create a Pandas DataFrame from. After lots of juggling (deleting irregular, lines, variable headers etc.) I got to a point where I have parsed each line as needed, but I am having trouble in converting it into a DataFrame. Please note that each line is of variable lengths and the number of elements in each line can be different.
Input
15.2' 4.3' 16.9' 4.0', GVW kips= 70.6, 9.5, 14.5, 14.1, 15.8, 16.7
3.2' 10.0' , GVW kips= 30.2, 9.5, 11.3, 12.0
Desired Output DataFrame (note that ' characters I have to get rid of, and the first number after GWV kips= not included in the DataFrame)
S1 S2 S3 S4 S5 W1 W2 W3 W4 W5 W6
15.2 4.3 16.9 4.0 Nan 9.5 14.5 14.1 15.8 16.7 Nan
3.2 10.0 Nan Nan Nan 30.2 9.5 11.3 12.0 Nan Nan
To parse one line
my_string = r"15.2' 4.3' 16.9' 4.0', GVW kips= 70.6, 9.5, 14.5, 14.1, 15.8, 16.7"
my_list = my_string.split("'") #get rid of " ' " characters
my_list = [l.split(',') for l in ','.join(my_list).split(' GVW kips= ')] # split the list into two parts one for "S" columns one for "W" columns
my_list = [list(filter(None, lst)) for lst in my_list] # get rid of '' empty strings
my_list = [[float(j) for j in i] for i in my_list] # convert everything to floats
my_list[1].pop(0) # get rid of first element after GVW kips=
this gives me the following two lists:
[[15.2, 4.3, 16.9, 4.0], [9.5, 14.5, 14.1, 15.8, 16.7]]
at this point I got stuck when converting these 2 lists, first one for columns S1 to S5, and the other for columns W1 to W6, into a DataFrame where missing elements should be shown with NaNs. And the operation so far is only for one line. I need to do the same for more than 1,000,000 lines.
I think I can create Series lists named W1 through W6 and S1 through S5, then append the values line by line. Then convert everything to a DataFrame when all Series are ready. The problem is in reality I have 30 W and 29 S columns, this would require me to maintain 59 lists for the whole run, which does not sound meaningful...
Is there a better way to build a DataFrame by reading a text file line by line, and using the output two lists for each line, where each line may be of different lengths?
Thanks!
A: This works
*
*one of the simplest ways to understand how I've build dictionary is get familiar with various options of data frame to_dict() formats
*I really saw a simple pattern, string is in two parts S and W delimited by a constant string. So use a re to get the two parts
*use zip to classify and make building dict keys simple
import re, io
import pandas as pd
import numpy as np
inp = """15.2' 4.3' 16.9' 4.0', GVW kips= 70.6, 9.5, 14.5, 14.1, 15.8, 16.7
3.2' 10.0' , GVW kips= 30.2, 9.5, 11.3, 12.0"""
# remove unwanted spaces and quotes
inp = inp.replace("'","").replace(",","")
d = {r:{f"{k}{c+1}":vv
# tokenise into S & W with "GVW kips=" being delimter
for k,v in zip(["S","W"], re.findall("^([\d. ]*)GVW kips= ([\d. ]*)$", s)[0])
# use re.split so multiple spaces are treated as one
for c, vv in enumerate(re.split("[ ]+", str(v)))
}
for r, s in enumerate(inp.split("\n"))}
pd.DataFrame(d).T.replace({"":np.nan})
output
S1 S2 S3 S4 S5 W1 W2 W3 W4 W5 W6
15.2 4.3 16.9 4.0 NaN 70.6 9.5 14.5 14.1 15.8 16.7
3.2 10.0 NaN NaN NaN 30.2 9.5 11.3 12.0 NaN NaN
A: Add NaN to satisfy the required number of columns. It is converted into a data frame after completing a million rows in a loop process. This method will be faster and more efficient.
s = 5
for i in range(s - len(my_list[0])):
my_list[0].append(np.NaN)
w = 6
for i in range(w - len(my_list[1])):
my_list[1].append(np.NaN)
new = pd.DataFrame(index=[], columns=[])
new = pd.concat([new, pd.Series(sum(my_list,[])).to_frame().T], axis=0, ignore_index=True)
cols = ['S1','S2','S3','S4','S5','W1','W2','W3','W4','W5','W6']
new.columns = cols
new
S1 S2 S3 S4 S5 W1 W2 W3 W4 W5 W6
0 15.2 4.3 16.9 4.0 NaN 9.5 14.5 14.1 15.8 16.7 NaN
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63607631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Distinguishing Between Click and Drag dispatchTouchEvent I am currently using dispatchTouchEvent to grab touch events, is there an easy way to distinguish between a click and a "drag" stylt gesture?
A: DispatchTouchEvent is called with a MotionEvent parameter. Method getAction within MotionEvent can return
*
*ACTION_DOWN
*ACTION_MOVE
*ACTION_UP
*ACTION_CANCEL
Then set on ACTION_DOWN flag isClick. If there is ACTION_MOVE clear isClick flag.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
isClick = true;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (isClick) {
//TODO Click action
}
break;
case MotionEvent.ACTION_MOVE:
isClick = false;
break;
default:
break;
}
return true;
}
A: set up a threshold limit.When you move the pointer within a small range make it recognized as a click or else a movement
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14419865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Cookies Not Consistently Being Shared Across Tabs In IE got a rather strange problem that I'm sure is a browser setting, so whilst it isn't strictly a programming issue, I was wondering if people here had come across it during their development work and could suggest a solution/cause.
My app is in MVC 2 and runs a central menu system with the links to the actual app screens all having a target="_blank" and so open either in new windows or new tabs, depending on how the user prefers through their browser settings. This all works fine on every system we use it on, apart from a new one - we're setting up a new Citrix desktop and we are getting strange behaviour when testing it. We can log on, ok, and navigate through the menus, but when we hit the menu links 90% of the time the new link opens with the login challenge, as if the browser no longer has the session cookie. However, when we go back to the main tab we are still logged in and can navigate around the menus fine. The other very odd thing is occassionally I can load a screen ok in the new tab and run it fine, but then opening it again from the menu fails and we again get the login challenge. Once I log on to one new tab, the rest open fine, which is even stranger.
I'm guessing this is some sort of tab isolation setting, but as it doesn't always seem to work. if there is one is it known to be a bit buggy? The browser is IE 8, which we use on all the other systems, fine. Any group policy settings that could be causing this as it happens on a user's login we're testing with, but not mine - I'm waiting on our network admin to get back to me regarding any GP differences between admins and users, but I thought I'd ask in here in case he can't see anything obvious.
Cheers - MH
A: It turns out this is an IE bug (no real surprise there) - when the browser spawns a new tab in a new worker process the new process doesn't have access to the session cookie. A few other people have found this and stopping the spawning of new processes, though not a great solution, seems to fix the issue. Note that this issue also occurs on the Yahoo website, and all other sites that use session cookies. Really not sure which combination of events and situations trigger this (on our system is only hits non-admin users - we've looked through our GPO rules but haven't found anything obvious), but I reckon MS really need to fix it because if it starts to trigger more often it could completely cripple IE.
Here's the link to temporarily bypass the issue, if you get hit by it, yourself.
http://blogs.msdn.com/b/askie/archive/2009/03/09/opening-a-new-tab-may-launch-a-new-process-with-internet-explorer-8-0.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12894794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Replace concat part of a string in typescript I have a variable string, because it is inside a textarea. A user can write anything. After that there's a date picker. When I select the date, the value will be written in the textarea after the first part of the string. I have this function on change of the picker
concatValue(){
let dataMsg = "";
let date: string = moment(dateTime).format('D MMM YYYY, h:mm');
dataMsg = ". " + date;
this.message += dataMsg;
}
The problem here, is that if I change date, the string keep concat and don't reset the before value. But I can't reset the entire this.message because it include other text. How can I do something like this? For example. First time
"Hello there at Thursday 15 October 2020, 19:00"
then i wanna change date:
"Hello there at Friday 16 October 2020, 15:00"
That's what I need instead of
"Hello there at Thursday 15 October 2020, 19:00"
"Hello there at Thursday 15 October 2020, 19:00 Friday 16 October 2020, 15:00"
A: I'm going to make my own minimal reproducible example so if you need to tweak it to apply to your use case, hopefully you can. Imagine I have this Foo class that takes a message and concats dates or times or something onto it:
class Foo {
message: string;
constructor(message: string) {
this.message = message;
}
concatDate() {
this.message += " @ " + new Date().toLocaleTimeString();
}
}
let f = new Foo("hello there");
console.log(f.message); // "hello there"
f.concatDate();
console.log(f.message); // "hello there @ 12:56:10 PM"
await new Promise(resolve => setTimeout(resolve, 2000));
f.concatDate();
console.log(f.message); // "hello there @ 12:56:10 PM @ 12:56:12 PM"
Oops, every time I call concatDate() it adds to the end of message. How can I fix it? Well, one idea is that you can try to look at message and strip off any date string if one is there. Like this:
class BadFixFoo {
message: string;
constructor(message: string) {
this.message = message;
}
concatDate() {
this.message = this.message.replace(/ @[^@]*$/, "") +
" @ " + new Date().toLocaleTimeString();
}
}
It kind of works:
f = new BadFixFoo("hello there");
console.log(f.message); // "hello there"
f.concatDate();
console.log(f.message); // "hello there @ 12:56:12 PM"
await new Promise(resolve => setTimeout(resolve, 2000));
f.concatDate();
console.log(f.message); // "hello there @ 12:56:14 PM"
Until it doesn't work:
f = new BadFixFoo("what if I use an @-sign in the message");
console.log(f.message); // "what if I use an @-sign in the message"
f.concatDate();
console.log(f.message); // "what if I use an @ 12:56:14 PM"
await new Promise(resolve => setTimeout(resolve, 2000));
f.concatDate();
console.log(f.message); // "what if I use an @ 12:56:16 PM"
See, the method I used to strip off the date just looked for the last @ sign (after a space) in the message and removed it and everything after it. But if the original message has an @ sign in it, then the stripping will mess it up. Oops. Maybe we can write an even more clever way of identifying a date string, but if the user can truly write anything for the original message, there's nothing we can do to stop them from writing an actual date string. Do we want to strip that off?
If not, you need to refactor so that you're not trying to forensically determine what the original message was. Instead, store it:
class GoodFoo {
originalMessage: string;
message: string;
constructor(message: string) {
this.originalMessage = message;
this.message = message;
}
concatDate() {
this.message = this.originalMessage + " @ " + new Date().toLocaleTimeString();
}
}
This means that concatDate() never tries to modify the current message. Instead, it copies the originalMessage and appends to that:
f = new GoodFoo("what if I use an @-sign in the message");
console.log(f.message); // "what if I use an @-sign in the message"
f.concatDate();
console.log(f.message); // "what if I use an @-sign in the message @ 12:56:16 PM"
await new Promise(resolve => setTimeout(resolve, 2000));
f.concatDate();
console.log(f.message); // "what if I use an @-sign in the mssage @ 12:56:18 PM"
Playground link to code
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64376485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jssor slider responsive Angular 2 I have followed this answer to add jssor in angular2. I have added below code of javascript into file and called in angular-cli.json.
jssor_1_slider_init = function() {
var jssor_1_options = {
$AutoPlay: true,
$AutoPlaySteps: 4,
$SlideDuration: 160,
$SlideWidth: 200,
$SlideSpacing: 3,
$Cols: 4,
$ArrowNavigatorOptions: {
$Class: $JssorArrowNavigator$,
$Steps: 1
},
$BulletNavigatorOptions: {
$Class: $JssorBulletNavigator$,
$SpacingX: 1,
$SpacingY: 1
}
};
var jssor_1_slider = new $JssorSlider$("jssor_1", jssor_1_options);
function ScaleSlider() {
var refSize = jssor_1_slider.$Elmt.parentNode.clientWidth;
if (refSize) {
refSize = Math.min(refSize, 809);
jssor_1_slider.$ScaleWidth(refSize);
}
else {
window.setTimeout(ScaleSlider, 30);
}
}
};
I observe that ScaleSlider() function is used for scale slider but its not calling.
How can I make it responsive in angular 2?
A: /*responsive code begin*/
/*remove responsive code if you don't want the slider scales while window resizing*/
function ScaleSlider() {
var refSize = jssor_1_slider.$Elmt.parentNode.clientWidth;
if (refSize) {
refSize = Math.min(refSize, 809);
jssor_1_slider.$ScaleWidth(refSize);
}
else {
window.setTimeout(ScaleSlider, 30);
}
}
ScaleSlider();
$Jssor$.$AddEvent(window, "load", ScaleSlider);
$Jssor$.$AddEvent(window, "resize", ScaleSlider);
$Jssor$.$AddEvent(window, "orientationchange", ScaleSlider);
/*responsive code end*/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42595139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Trouble avoiding a Loop-switch sequence I am an Android/Java beginner, not that much with coding but rather with the language(s).
My problem:
I am drawing a graph (for some statistical analysis) with canvas.drawLine() with different colors for each line. The color depends on the value of an array. That array(list) holds custom objects that have about 20 variables of different types.
At some point, I need a switch to get the right type for each draw-call, but for the entire loop, that switch has the same outcome. As I am almost finished with the program I am looking for performance issues and this is one.
The graph draws at least 1000 lines so the switch runs 1000 times for the same result.
If I had arrays and not custom objects i could simply use an int to access the different array values. But there is no way to rewrite it so that the objects can be avoided (would mess up the code big time at other places).
Now I read about polymorphism and reflections but... To be honest, I dont want to implement something that I dont completely understand and that is not bulletproof (reflections are said to be prone to error ?!)
My current solution is that I simply created a custom drawing method for each case. I have one switch before the loop and then the drawing method with the right getter is working. It works, however it seems crazy to have 10 methods with only one line different.
Now there is also the abstract class thing but it confuses me a bit and im wondering if those overwritten methods wont cause more performance trouble than the switch. I read something about what java does in the end and that those cross-class method calls could cost performance (i admit it was something about inner/nested classes calling a getter of their outter class).
I want the code to be as short and readable as possible, so I would like to have it all in one code-block (kinda) rather than spread across different classes but thats just a personal preference. The most important thing is, that I completely understand what I am implementing. I dont want some example that I copy and paste with 'enter your method here' and see it working but dont know why or how.
So I am actually more interested in the theoretical how I should do it than actual code snippets (ofc the snippets wont hurt ;) )
PS: Should I have a code smell somewhere, feel free to mention it.
Some code, simplyfied and focused on the problem
Class MyObj {
int x;
int y;
double value_doub;
short value_short;
// getters and setters etc
}
private void draw_graph(int switchcase) {
MyObj mObj;
int x;
int y;
double value;
for(int i = 0; i < amount_of_values; i++) {
mObj = mArrayList.get(i);
x = mObj.getx();
y = mObj.gety();
switch(switchcase) {
case 0:
value = mObj.get_value_doub();
//alternatively, direct field access
value = mObj.value_doub;
color = calc_color(value, scale_for_this_type);
break;
case 1:
value = (double) mObj.get_value_short();
//alternatively, direct field access
value = (double) mObj.value_short;
color = calc_color(value, scale_for_this_type);
break;
// etc... 10+ cases
}
drawLine(last_x, last_y, x, y, color);
}
}
A: Your code is OK, but not very object-oriented. I would probably use some kind of Drawer interface, and pass the appropriate implementation, rather than an int, to the draw_graph method (which I would rename drawGraph to respect naming conventions):
public interface Drawer {
void draw(MyObj obj, Graphics g);
}
...
private void drawGraph(Drawer drawer) {
for(int i = 0; i < amountOfValues; i++) {
MyObj obj = arrayList.get(i);
drawer.draw(obj, g);
}
}
...
class Drawer1 implements Drawer {
@Override
public void draw(MyObj obj, Graphics g) {
// same code as in case 1 of the switch
}
}
class Drawer2 implements Drawer {
@Override
public void draw(MyObj obj, Graphics g) {
// same code as in case 2 of the switch
}
}
If all the drawers share some code, then make them all extend a base AbstractDrawer class.
A: The x,y, and value are properties of MyObj. What does calc_color do, and where does scale_for_this_type come from? Could that work be done within, or largely within MyObj based upon it's fields?? If so, your loop could pretty much call myObj.drawLineYouFigureOutTheColor(perhapsAnArgumentOrTwoHere). You'd have to track last_x and last_y somewhere.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8464587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: #1005 - Can't create table 'test_db.demandes_gardes' (errno: 150) (Details…) I can't execute this query on phpmyadmin for upgrading my sql test_db:
CREATE TABLE IF NOT EXISTS `demandes_gardes` (
`id` INT NOT NULL AUTO_INCREMENT,
`nom` VARCHAR(255) NULL,
`prenom` VARCHAR(255) NULL,
`matricule` VARCHAR(255) NULL,
`chambre` VARCHAR(255) NULL,
`autre` TEXT NULL,
`garde_id` INT NOT NULL,
`statut_id` INT NOT NULL,
`created` DATETIME NULL,
`updated` DATETIME NULL,
PRIMARY KEY (`id`),
INDEX `fk_demandes_gardes_gardes1_idx` (`garde_id` ASC),
INDEX `fk_demandes_gardes_statuts1_idx` (`statut_id` ASC),
CONSTRAINT `fk_demandes_gardes_gardes1`
FOREIGN KEY (`garde_id`)
REFERENCES `gardes` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_demandes_gardes_statuts1`
FOREIGN KEY (`statut_id`)
REFERENCES `statuts` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I get :
#1005 - Can't create table 'test_db.demandes_gardes' (errno: 150)
Any help please ?
Thank you
A: Please ensure the statuts and gardes tables have the id column set as a primary key. I tested the same code and only received the 1005 error when one of the foreign keys was not a primary key in its own table. This is assuming there is a valid statuts and gardes table each with an integer id column.
ALTER TABLE `statuts`
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (`id`);
ALTER TABLE `gardes`
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (`id`);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33715965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Postgres DB migration fails with "violates not-null constraint" I am trying to upgrade Netbox (https://github.com/digitalocean/netbox) from older version (2.3.7) to newer one (2.4.3) by using upgrade script which include the step manage.py migrate.
And on this step it fails with error:
vagrant@ubuntu-xenial:/opt/netbox/netbox$ python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, circuits, contenttypes, dcim, extras, ipam, secrets, sessions, taggit, tenancy, users, virtualization
Running migrations:
Applying auth.0009_alter_user_last_name_max_length...Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, auth, 0009_alter_user_last_name_max_length, 2018-09-04 17:29:15.531382+00).
The postgres DB has already been filled.
If I run on the empty DB upgrade works normally.
But as a newbie I don't have an idea how to tshoot this issue.
A: I believe this occurs when you are running Postgres 9.x and the data you imported came from Postgres 10.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52171466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery Slick plugin not resizing after parent resizes I have a project with a collapsable sidebar navigation, with the content filling the remaining space; when the navigation is collapsed, the content fills the whole screen.
I'm using jQuery Slick to display some snippets of text, and for the most part, responsively it works great. However, whenever I toggle the navigation, Slick doesn't respond to the new width of it's parent, showing part of the next slide instead of filling the screen.
What can I do to fix this?
Here is a jsfiddle demonstrating the issue:
http://jsfiddle.net/b82x7rr2/
And here's some code:
<nav>
<ul>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
<li><a href="#">Page 3</a></li>
</ul>
</nav>
<div class="wrapper">
<p><a href="#" class="close">Toggle Navigation</a></p>
<div class="slider">
<div>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</p>
</div>
<div>
<p>Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</p>
</div>
</div>
</div>
<style>
nav{
width: 300px;
position:fixed;
top:0;
left:0;
height:100%;
background:#000;
}
.wrapper{
padding:0 0 0 300px;
text-align:center;
}
p{
margin:10px;
}
body.active nav{
display:none;
}
body.active .wrapper{
padding:0;
}
</style>
<script type="text/javascript">
$().ready(function(){
$(".slider").slick();
$(".close").on("click", function(){
if( !$("body").hasClass("active") ){
$("body").addClass("active");
}else{
$("body").removeClass("active");
}
});
});
</script>
A: Try this: http://jsfiddle.net/b82x7rr2/2/
$().ready(function(){
$(".slider").slick();
$(".close").on("click", function(){
if( !$("body").hasClass("active") ){
$("body").addClass("active");
$(".slider").slick('slickRemove');
}else{
$("body").removeClass("active");
$(".slider").slick('slickRemove');
}
});
});
The $(".slider").slick('slickRemove'); removes the following slide from the screen, without reloading the current slide
Even more concise fiddle: http://jsfiddle.net/b82x7rr2/3/
$().ready(function(){
$(".slider").slick();
$(".close").click(function(){
$("body").toggleClass("active");
$(".slider").slick('slickRemove');
}
);
});
A: The only way i found to bypass this issue is
$(".slider").slick('getSlick').slickGoTo(slick.slickCurrentSlide());
everytime you toggle navigation.
here is the fiddle
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29143220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Twitter get search tweets API not working with hash tag Hi right now I am trying to do a keyword search with hashtag using Twitter API. This is the url I am using.
https://api.twitter.com/1.1/search/tweets.json?q=%23bookmyshow
But I am not getting any result. From yesterday I was trying to sort out this issue. Any one can help me to fix this issue. This is code I am using for search
<?php
ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');
$oauth_access_token = '2329813950-XGm12JrlbxOIHF6mmDPhF8l2ddDHa2PEKPdHYHp';
$oauth_access_token_secret = '1g88J15Qxl24SOn6arfXgAqGH0N1VthxvDIyrK2dZBfu1';
$consumer_key = 'mU6nzH298ZoZCdYaqbyzA';
$consumer_secret = 'gIDEYBiruLf29VEq7Zx75U7bFJrkia9HV8SSw0qjlI';
$token = '2329813950-XGm12JrlbxOIHF6mmDPhF8l2ddDHa2PEKPdHYHp';
$token_secret = '1g88J15Qxl24SOn6arfXgAqGH0N1VthxvDIyrK2dZBfu1';
$consumer_key = 'mU6nzH298ZoZCdYaqbyzA';
$consumer_secret = 'gIDEYBiruLf29VEq7Zx75U7bFJrkia9HV8SSw0qjlI';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/search/tweets.json'; // api call path api.twitter.com/1.1/search/tweets.json
$query = array( // query parameters
'q' => '%23bookmyshow',
'count' => '2'
);
$oauth = array(
'q' => '%23bookmyshow',
'count' => 2,
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
$options = array(
CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url . '?q=%23bookmyshow&count=2',
CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
//print_r($twitter_data);
echo "<pre>";
print_r(json_decode($json));
?>
This file TwitterAPIExchange.php I got from Github.
A: It's not required to use %23 in Search Query for Search Values `.
Instead of 'q' => '%23bookmyshow', use 'q' => 'bookmyshow'.
Also, You haven't request Twitter to get tweets. Read this Documentation. If this is your Token secret, i would suggest you to reset your keys right now. Go to Twitter Developer page to access your apps & reset it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21626318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-7"
}
|
Q: Removing repeated element from a list I am trying to remove the repeated elements from a list:
li = [11, 11, 2, 3, 4]
I am trying in these ways:
Way 1:
li = [x for x in li if x!=11]
Way 2:
for x in range(0,len(li)):
if x==11:
li.remove(x)
Are there any built-in functions to do this job?
A: Edit:
I'm sorry, I misread your question originally.
What you really want is collections.Counter and a list comprehension:
>>> from collections import Counter
>>> li= [11, 11, 2, 3, 4]
>>> [k for k, v in Counter(li).iteritems() if v == 1]
[3, 2, 4]
>>>
This will only keep the items that appear exactly once in the list.
If order does not matter, then you can simply use set:
>>> li = [11, 11, 2, 3, 4]
>>> list(set(li))
[3, 2, 11, 4]
>>>
Otherwise, you can use the .fromkeys method of collections.OrderedDict:
>>> from collections import OrderedDict
>>> li= [11, 11, 2, 3, 4]
>>> list(OrderedDict.fromkeys(li))
[11, 2, 3, 4]
>>>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26819135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Different Tkinter Canvases, with an image background, switch with a quick white flash I am trying to make a game using tkinter GUI. My aim is to make different Canvas, with same or different images as a background, for different menus/screens.
But I have noticed that when I switch between different menus (canvases), there is a quick white flash during the switching which is undesirable. As far as I know, this is because when I "pack_forget" the previous canvas and pack the new one, the is a small difference between the two events
But I want the switching to be smooth because such a flickering doesn't look good in a game.
I have attached a code below. The code is a bit long. Actually I tried to reduce it as much as I could. So the code below is the minimum required code to check the problem.
This is what you should do:
*
*Run the program and click "New Game".
*Then click the 'Back' arrow shown at the bottom of the window.
*If you are unable to notice the flickering (or you may say "A quick white flash"), then keep repeating step 1 and 2.
The Image for the canvas background is attached here:
Image for Canvas background
from tkinter import *
from PIL import Image, ImageTk
from functools import partial
class DiceGame(Tk):
def __init__(self):
super(DiceGame, self).__init__()
self.title("Dice Cricket")
self.geometry('980x660+200-60')
self.state('zoomed')
self.font1 = ('Algerian', 95, 'bold')
self.font2 = ('Comic Sans MS', 50, 'bold')
self.font3 = ('Comic Sans MS', 40, 'bold')
self.font4 = ('Comic Sans MS', 30, 'bold')
self.font5 = ('Comic Sans MS', 25, 'bold')
self.bgcolor = '#366649'
self.background1 = PhotoImage(file = 'dicepic9.png')
self.back_image = PhotoImage(file = "back arrow.png").subsample(7,7)
self.MainMenu()
self.Actice_Window = "MainMenu"
def gameTitle(self, root):
title_Label = Label(root,
text = "Dice Cricket",
font = self.font1,
bg = self.bgcolor,
fg = 'yellow')
title_Label.grid(row = 0, column = 1, pady = 15, ipadx = 100)
def backbutton(self, root):
self.back_Label = Label(root,
text = "Back",
font = self.font5,
fg = "Yellow",
bg = self.bgcolor,
image = self.back_image,
compound = LEFT)
return self.back_Label
def MainMenu(self):
self.MainMenu_Canvas = Canvas(self, bg = self.bgcolor, highlightthickness = 0)
self.MainMenu_Canvas.pack(fill = BOTH, expand = True)
self.MainMenu_Canvas.create_image(2, 2, anchor = NW, image = self.background1)
self.gameTitle(self.MainMenu_Canvas)
self.MainMenu_Frame = Frame(self.MainMenu_Canvas)
self.MainMenu_Frame.grid(row = 1, column = 1, pady = 10, ipadx = 20)
self.MainMenu_Label = Label(self.MainMenu_Frame,
text = "Main Menu",
font = self.font2,
bg = self.bgcolor,
fg = 'orange')
self.MainMenu_Label.pack(fill = X, pady = (0,0))
self.Options_Frame = Frame(self.MainMenu_Frame, bg = 'gray10', bd = 4, relief = GROOVE)
self.Options_Frame.pack(fill = X, ipady = 5, ipadx = 60)
label1 = Label(self.Options_Frame, text = "New Game", font = self.font4, fg = "light green", bg = "gray10")
label1.pack()
label1.bind('<Button-1>', self.NewGame_Menu)
def NewGame_Menu(self, event):
self.Actice_Window = "NewGame Menu"
self.MainMenu_Canvas.pack_forget()
self.NewGameMenu_Canvas = Canvas(self, bg = self.bgcolor, highlightthickness = 0)
self.NewGameMenu_Canvas.pack(fill = BOTH, expand = True)
self.NewGameMenu_Canvas.create_image(0, 0, anchor = NW, image = self.background1)
self.gameTitle(self.NewGameMenu_Canvas)
self.NewGame_Frame = Frame(self.NewGameMenu_Canvas, bg = self.bgcolor)
self.NewGame_Frame.grid(row = 1, column = 1, pady = 10)
self.selection_Label = Label(self.NewGame_Frame, text = "Select Game Type", font = self.font3, fg = "Silver", bg = self.bgcolor)
self.selection_Label.pack()
self.Matchtype_Frame = Frame(self.NewGame_Frame, bg = 'gray10', bd = 4, relief = GROOVE)
self.Matchtype_Frame.pack(ipadx = 60, ipady = 10, pady = 15)
label2 = Label(self.Matchtype_Frame, text = "Quick Match", font = self.font4, fg = "light green", bg = "gray10")
label2.pack()
self.back1 = self.backbutton(self.NewGameMenu_Canvas)
self.back1.grid(row = 2, column = 1, sticky = W, padx = 190, pady = 10)
self.back1.bind('<Button-1>', self.Go_Back)
def Go_Back(self, event):
if self.Actice_Window == "NewGame Menu":
self.NewGameMenu_Canvas.pack_forget()
self.MainMenu_Canvas.pack(fill = BOTH, expand = True)
dice = DiceGame()
dice.mainloop()
A: It is because you remove and recreate the canvases when switching canvas.
Below is a modified code based on yours:
*
*create canvases once
*use place() instead of pack() on canvases
*create a class method to raise a canvas to the front
from tkinter import *
from PIL import Image, ImageTk
from functools import partial
class DiceGame(Tk):
def __init__(self):
super(DiceGame, self).__init__()
self.title("Dice Cricket")
self.geometry('980x660+200-60')
self.state('zoomed')
self.font1 = ('Algerian', 95, 'bold')
self.font2 = ('Comic Sans MS', 50, 'bold')
self.font3 = ('Comic Sans MS', 40, 'bold')
self.font4 = ('Comic Sans MS', 30, 'bold')
self.font5 = ('Comic Sans MS', 25, 'bold')
self.font6 = ('Comic Sans MS', 15, 'bold')
self.bgcolor = '#366649'
self.background1 = PhotoImage(file = 'dicepic9.png')
self.back_image = PhotoImage(file = "back arrow.png").subsample(7,7)
self.MainMenu_Canvas = self.NewGameMenu_Canvas = None ###
self.MainMenu()
def gameTitle(self, root):
title_Label = Label(root,
text = "Dice Cricket",
font = self.font1,
bg = self.bgcolor,
fg = 'yellow')
title_Label.grid(row = 0, column = 1, pady = 15, ipadx = 100)
def createLabels(self, frame, LabelList, Labeltexts):
for i in range(len(Labeltexts)):
label = Label(frame, text = Labeltexts[i], font = self.font4, fg = 'light green', bg = 'gray10')
label.pack(fill = X)
LabelList.append(label)
LabelList[0].pack_configure(pady = (10,0))
self.selection(LabelList)
def selection(self, LabelList):
for label in LabelList:
label.bind("<Enter>", partial(self.color_config, label, "maroon", "pink"))
label.bind("<Leave>", partial(self.color_config, label, "light green", "grey10"))
def color_config(self, widget, color1, color2, event):
widget.configure(foreground = color1, bg = color2)
def backbutton(self, root):
self.back_Label = Label(root,
text = "Back",
font = self.font5,
fg = "Yellow",
bg = self.bgcolor,
image = self.back_image,
compound = LEFT)
return self.back_Label
### raise a canvas to the front
def raise_canvas(self, canvas):
canvas.tk.call("raise", canvas)
def MainMenu(self):
self.Actice_Window = "MainMenu" ### moved from __init__()
if self.MainMenu_Canvas is None:
self.MainMenu_Canvas = Canvas(self, bg = self.bgcolor, highlightthickness = 0)
###self.MainMenu_Canvas.pack(fill = BOTH, expand = True)
self.MainMenu_Canvas.place(relwidth=1, relheight=1) ###
self.MainMenu_Canvas.create_image(0, 0, anchor = NW, image = self.background1)
self.gameTitle(self.MainMenu_Canvas)
self.MainMenu_Frame = Frame(self.MainMenu_Canvas)
self.MainMenu_Frame.grid(row = 1, column = 1, pady = 10, ipadx = 20)
self.MainMenu_Label = Label(self.MainMenu_Frame,
text = "Main Menu",
font = self.font2,
bg = self.bgcolor,
fg = 'orange')
self.MainMenu_Label.pack(fill = X, pady = (0,0))
self.Options_Frame = Frame(self.MainMenu_Frame, bg = 'gray10', bd = 4, relief = GROOVE)
self.Options_Frame.pack(fill = X, ipady = 5, ipadx = 60)
mainLabels = []
Labeltexts = ["New Game", "Load Game", "Hall of Fame", "Options", "Credits", "Exit Game"]
self.createLabels(self.Options_Frame, mainLabels, Labeltexts)
mainLabels[0].bind('<Button-1>', self.NewGame_Menu)
self.raise_canvas(self.MainMenu_Canvas) ###
def NewGame_Menu(self, event):
self.Actice_Window = "NewGame Menu"
###self.MainMenu_Canvas.pack_forget()
if self.NewGameMenu_Canvas is None:
self.NewGameMenu_Canvas = Canvas(self, bg = self.bgcolor, highlightthickness = 0)
###self.NewGameMenu_Canvas.pack(fill = BOTH, expand = True)
self.NewGameMenu_Canvas.place(relwidth=1, relheight=1) ###
self.NewGameMenu_Canvas.create_image(0, 0, anchor = NW, image = self.background1)
self.gameTitle(self.NewGameMenu_Canvas)
self.NewGame_Frame = Frame(self.NewGameMenu_Canvas, bg = self.bgcolor)
self.NewGame_Frame.grid(row = 1, column = 1, pady = 10)
self.selection_Label = Label(self.NewGame_Frame, text = "Select Game Type", font = self.font3, fg = "Silver", bg = self.bgcolor)
self.selection_Label.pack()
self.Matchtype_Frame = Frame(self.NewGame_Frame, bg = 'gray10', bd = 4, relief = GROOVE)
self.Matchtype_Frame.pack(ipadx = 60, ipady = 10, pady = 15)
newGameLabels = []
newGameLabelsText = ["Quick Match", "Bilateral Series", "Tournament", "Practice"]
self.createLabels(self.Matchtype_Frame, newGameLabels, newGameLabelsText)
self.back1 = self.backbutton(self.NewGameMenu_Canvas)
self.back1.grid(row = 2, column = 1, sticky = W, padx = 190, pady = 10)
self.back1.bind('<Button-1>', self.Go_Back)
self.raise_canvas(self.NewGameMenu_Canvas) ###
def Go_Back(self, event):
if self.Actice_Window == "NewGame Menu":
###self.NewGameMenu_Canvas.pack_forget()
###self.MainMenu_Canvas.pack(fill = BOTH, expand = True)
self.raise_canvas(self.MainMenu_Canvas) ###
dice = DiceGame()
dice.mainloop()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65195606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Powershell curl double quotes I am trying to invoke a curl command in powershell and pass some JSON information.
Here is my command:
curl -X POST -u username:password -H "Content-Type: application/json" -d "{ "fields": { "project": { "key": "key" }, "summary": "summary", "description": "description - here", "type": { "name": "Task" }}}"
I was getting globbing errors and "unmatched braces" and host could not be resolved, etc.
Then I tried prefixing the double quotes in the string with the backtick character, but it could not recognize the - character in the description json field
thanks
EDIT 1:
When I wrote the curl command in a regular batch file, I used double quotes and no single quotes. Also, in the -d string, I escaped all the double quotes with \ and the command worked.
In this case, my curl is actually pointing to curl.exe. I specified the path, just didn't list it here. Also I tried adding single quotes around -d and I got:
curl: option -: is unknown curl: try 'curl --help' or 'curl --manual' for more information
Seems like it cannot recognize the - character in the JSON
A: Easy way (for simple testing):
curl -X POST -H "Content-Type: application/json" -d '{ \"field\": \"value\"}'
A: Pipe the data into curl.exe, instead of trying to escape it.
$data = @{
fields = @{
project = @{
key = "key"
}
summary = "summary"
description = "description - here"
type = @{
name = "Task"
}
}
}
$data | ConvertTo-Json -Compress | curl.exe -X POST -u username:password -H "Content-Type: application/json" -d "@-"
curl.exe reads stdin if you use @- as your data parameter.
P.S.: I strongly suggest you use a proper data structure and ConvertTo-Json, as shown, instead of building the JSON string manually.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33526823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Python using lxml to write an xml file with system performance data I am using the python modules lxml and psutil to record some system metrics to be placed in an XML file and copied to a remote server for parsing by php and displayed to a user.
However, lxml is giving me some trouble on pushing some variables, objects and such to the various parts of my XML.
For example:
import psutil, os, time, sys, platform
from lxml import etree
# This creates <metrics>
root = etree.Element('metrics')
# and <basic>, to display basic information about the server
child1 = etree.SubElement(root, 'basic')
# First system/hostname, so we know what machine this is
etree.SubElement(child1, "name").text = socket.gethostname()
# Then boot time, to get the time the system was booted.
etree.SubElement(child1, "boottime").text = psutil.boot_time()
# and process count, see how many processes are running.
etree.SubElement(child1, "proccount").text = len(psutil.pids())
The line to get the system hostname works.
However the next two lines to get boot time and process count error out, with:
>>> etree.SubElement(child1, "boottime").text = psutil.boot_time()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 921, in lxml.etree._Element.text.__set__ (src/lxml/lxml.etree.c:41344)
File "apihelpers.pxi", line 660, in lxml.etree._setNodeText (src/lxml/lxml.etree.c:18894)
File "apihelpers.pxi", line 1333, in lxml.etree._utf8 (src/lxml/lxml.etree.c:24601)
TypeError: Argument must be bytes or unicode, got 'float'
>>> etree.SubElement(child1, "proccount").text = len(psutil.pids())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 921, in lxml.etree._Element.text.__set__ (src/lxml/lxml.etree.c:41344)
File "apihelpers.pxi", line 660, in lxml.etree._setNodeText (src/lxml/lxml.etree.c:18894)
File "apihelpers.pxi", line 1333, in lxml.etree._utf8 (src/lxml/lxml.etree.c:24601)
TypeError: Argument must be bytes or unicode, got 'int'
So, here's what my XML looks like as printed:
>>> print(etree.tostring(root, pretty_print=True))
<metrics>
<basic>
<name>mercury</name>
<boottime/>
<proccount/>
</basic>
</metrics>
So, is there anyway to push floats and ints to xml text like I need? Or am I doing this completely wrong?
Thanks for any help you can provide.
A: The text field is expected to be unicode or str, not any other type (boot_time is float, and len() is int).
So just convert to string the non-string compliant elements:
# First system/hostname, so we know what machine this is
etree.SubElement(child1, "name").text = socket.gethostname() # nothing to do
# Then boot time, to get the time the system was booted.
etree.SubElement(child1, "boottime").text = str(psutil.boot_time())
# and process count, see how many processes are running.
etree.SubElement(child1, "proccount").text = str(len(psutil.pids()))
result:
b'<metrics>\n <basic>\n <name>JOTD64</name>\n <boottime>1473903558.0</boottime>\n <proccount>121</proccount>\n </basic>\n</metrics>\n'
I suppose the library could do the isinstance(str,x) test or str conversion, but it was not designed that way (what if you want to display your floats with leading zeroes, truncated decimals...).
It operates faster if the lib assumes that everything is str, which it is most of the time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39538576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SolrJ - Indexing multiple classes and ensuring document uniqueness I want to use SolrJ for indexing a set of Java classes. Each class instance is determined by its id which is unique within a class. However, by using the Solr @Field annotation for making Solr documents from these classes it turns out that this annotation doesn't guarantee uniqueness of the created documents stored in the Solr index (same id values may belong to multiple classes).
I tried combining the annotation approach with the Solr UUID data type for generating unique id values into a specified field in the solr schema, but with no success.
As a result, I created a simple annotation mechanism not so different from the SolrJ one, which guarantees uniqueness across multiple classes. This is done by combining object class name and its id to get a sort of UUID which is then stored in the Solr schema.
I'm not sure if I'm not missing something, so I would like to know if the working solution described above is good enough for my case or if there are any cleaner/better alternatives.
A: I think this is a valid approach. We are doing something similar with multiple indexes at our location. For example we have 4 different types of items in our database that we are loading into a common schema in the index and we prefix the database table id with the first two unique letters of the type to ensure that it will be unique.
Also IMO, indexing multiple distinct types in one index is really a preference and not a rule of thumb as indicated in the links below
*
*Single schema versus multiple schemas in solr for different document types
*Running Multiple Indexes
A: Typically one POJO will correspond to one schema and one Solr core. I am not sure why you would want to index different POJOs into one Solr core.
But with that said, your class name approach should work fine. Else you can declare a static CLASS_ID field in each one of your classes, keep them different for different classes and form the Solr document ID by concatenating like id:CLASS_ID.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15030176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's wrong with this Ruby dependency? I am trying to use source2swagger on OSX 10.7.5
It depends on "json" so I am installing that, then trying to run as below.
machine:source2swagger jpbeuc1$ sudo gem install json
Password:
Building native extensions. This could take a while...
Successfully installed json-1.7.7
1 gem installed
Installing ri documentation for json-1.7.7...
Installing RDoc documentation for json-1.7.7...
machine:source2swagger jpbeuc1$ bin/source2swagger
bin/source2swagger:4:in `require': no such file to load -- json (LoadError)
from bin/source2swagger:4
Can anyone tell me what's not working here and how to make source2swagger see "json"?
A: You have source2swagger installed in your local and gems are installed in root. So your source2swagger which needs json can't access those gem which are installed in root. So I recommend to gems in local always and avoid using sudo for installing gems. To manage gems in local I suggest to use RVM.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15138836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sprockets find_asset doesn't translate files within rake task I have a rails application using react-rails with jsx assets, and I would like to see the pure js translation of these files within a rake task.
Within the rails console, I can achieve this with the line Rails.application.assets.find_asset(jsx_file_path).to_s
However, when I put this line in a rake task, it returns the untranslated contents of the jsx file (console and the rake task were executed in the same rails environment). Why does sprockets behave differently in the rails console and a rake task, and how can I configure it to behave the same in the rake task?
A: Fixed: I needed my rake task to depend on :environment so that the rails application gets initialized before the task is run.
After changing task :my_task do to
task :my_task => :environment do everything works the same in the rake task as it does in the console.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45357881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I download images from a list of links? I have a list of links to images (about 5000 lines), and I need to know how I can download all it fast. Please help me with my code:
import concurrent.futures
import urllib.request
catname = 'amateur'
def getimg (count, endcount):
while (count < endcount):
urllib.request.urlretrieve(URLS[count], catname+'/images/'+catname+str(count)+'.jpg')
URLS[count] = catname+'/images/'+catname+str(count)+'.jpg'
count = count + 1
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as e:
e.submit(getimg, 0, 5000)
It works fine but slow.
A: Your code download 5000 images 50 times. Try following:
import concurrent.futures
import urllib.request
catname = 'amateur'
def getimg(count):
localpath = '{0}/images/{0}{1}.jpg'.format(catname, count)
urllib.request.urlretrieve(URLS[count], localpath)
URLS[count] = localpath
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as e:
for i in range(5000):
e.submit(getimg, i)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18604215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to reuse bookmarks contextmenu. (Contextmenu commands not issued.) I have a Firefox addon that creates several buttons with dropdowns. Each dropdown contains several menu items representing bookmarks.
Almost identical to bookmark folders or tags on the bookmarks toolbar (after having dragged them there) which also have dropdowns with bookmark menu items.
I would like to reuse bookmarks contextmenu already existing on those latter dropdown menu-items.
I have found this way of doing it partly, but I'l stuck (see below how):
var mi = doc.createElementNS(XUL_NS,'menuitem');
mi.setAttribute('class', 'menuitem-iconic bookmark-item menuitem-with-favicon');
mi.setAttribute('scheme', 'http');
//this gets the existing contextmenu all right
mi.setAttribute("context", "placesContext");
//this.pp = my own dropdown menupopup,
this.pp.appendChild(mi);
Resulting contextmenu screenshot:
First (minor) problem:
Everything is grayed out until I first right-click on one of the latter dropdown items before right-clicking my own.
Second (major) problem:
When hitting a command/menu-item of the placesContext menu, the commands (e.g. "Open" or "Open in new tab") are not done. Nothing happens. Is there some attributes that my menu-item misses so that the "placesCmd_open" ignores it or do I really have to override the existing event listeners of placesContext or even different?!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28805418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Airflow BashOperator doesn't work but PythonOperator does I seem to have a problem with BashOperator. I'm using Airflow 1.10 installed on CentOS in a Miniconda environment (Python 3.6) using the package on Conda Forge.
When I run airflow test tutorial pyHi 2018-01-01 the output is "Hello world!" as expected.
However, when I run airflow test tutorial print_date 2018-01-01 or
airflow test tutorial templated 2018-01-01 nothing happens.
This is the Linux shell output:
(etl) [root@VIRT02 airflow]# airflow test tutorial sleep 2015-06-01
[2018-09-28 19:56:09,727] {__init__.py:51} INFO - Using executor SequentialExecutor
[2018-09-28 19:56:09,962] {models.py:258} INFO - Filling up the DagBag from /root/airflow/dags
My DAG configuration file, which is based on the Airflow tutorial, is shown below.
from airfl ow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from datetime import datetime, timedelta
import test
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2010, 1, 1),
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5),
}
dag = DAG(
'tutorial',
'My first attempt',
schedule_interval=timedelta(days=1),
default_args=default_args,
)
# t1, t2 and t3 are examples of tasks created by instantiating operators
t1 = BashOperator(
task_id='print_date',
bash_command='date',
dag=dag)
t2 = BashOperator(
task_id='sleep',
bash_command='sleep 5',
retries=3,
dag=dag)
templated_command = """
{% for i in range(5) %}
echo "{{ ds }}"
echo "{{ macros.ds_add(ds, 7)}}"
echo "{{ params.my_param }}"
{% endfor %}
"""
t3 = BashOperator(
task_id='templated',
bash_command=templated_command,
params={'my_param': 'Parameter I passed in'},
dag=dag)
t4 = BashOperator(
task_id='hi',
bash_command = 'test.sh',
dag=dag,
)
t5 = PythonOperator(
task_id='pyHi',
python_callable=test.main,
dag=dag,
)
t2.set_upstream(t1)
t3.set_upstream(t1)
A: Technically it's not that the BashOperator doesn't work, it's just that you don't see the stdout of the Bash command in the Airflow logs. This is a known issue and a ticket has already been filed on Airflow's issue tracker: https://issues.apache.org/jira/browse/AIRFLOW-2674
The proof of the fact that BashOperator does work is that if you run your sleep operator with
airflow test tutorial sleep 2018-01-01
you will have to wait 5 seconds before it terminates, which is the behaviour you'd expect from the Bash sleep command.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52606062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: What's the difference in Github between fixing, resolving and closing and issue? Here in Github it refrences 3 ways to discuss a ticket:
https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue
*
*close
*resolve
*fix
I was wondering what the techincally differences are between these 3, they all sound very similar to me.
A: The list you are quoting is not a list of options presented in a menu, it is a list of different ways of saying the same thing.
These are all just keywords which Github recognises when it looks at the description. Different people use different terms, so rather than forcing people to use (and remember) one preferred term, they include multiple possibilities.
The examples below the list use different keywords just for illustration. All the keywords are interchangeable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69362713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to select fonts more specifically in cairo? In cairo, fonts can be specified by their family name, e.g. 'HelveticaNeueLTStd'. Then, weights and styles can be defined by cairo.FONT_WEIGHT_[NORMAL|BOLD] and cairo.FONT_SLANT_[NORMAL|OBLIQUE|ITALIC], which are constants with integer values. Only these 2 and 3 options are built in. I am wondering, how to select specific weights and styles in case the family have more of them? E.g. Light, Semi-bold, etc.
I am using pycairo 1.10.0 in python 2.7, although these things looks the same in any language.
I could find the solution by guessing, so I will answer my question, but still I am wondering if this is the standard way of doing.
A: Font files have various names and other annotations. In FontForge, you can find these listed in menu Element > Font info. Here as I found cairo is able to identify the font by its TTF names > Family or which is the same its WindowsString. In case of Adobe's Helvetica Neue light this string has the value 'HelveticaNeueLT Std Lt'. Then selecting the font by this name, and setting the slant and weight to normal, the light weight will be used:
context.select_font_face('HelveticaNeueLT Std Lt', \
cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
It is possible to find font names by many softwares. On Linux fontconfig is able to list fonts, and the name in the second column what cairo recognizes:
$ fc-list | grep HelveticaNeue
...
/usr/share/fonts/.../HelveticaNeueLTStd-Lt.otf: Helvetica Neue LT Std,HelveticaNeueLT Std Lt:style=45 Light,Regular
...
$ fc-list | sed 's/.*:\(.*,\|\s\)\(.*\):.*/\2/'
...
HelveticaNeueLT Std Lt
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28729589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Button with Navigation to other page in navbar materialize react I wanted to insert buttons in the navbar of materialize to navigate to other pages. How can I create a button that helps me to open another page. I used the "Linked to" from react-router, but it doesn't work. Thank you very much for your response
import { Link } from "react-router-dom";
<nav>
<div class="nav-wrapper blue lighten-2">
<a class="brand-logo left">
<img scr="/images/logo_small.png"></img>
</a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li>
<a href="teechrworks.html">How teechr works?</a>
</li>
<li>
<a href="aboutus.html">About us</a>
</li>
<ul>
<li>
<Link to="/chooseachatbottype">Get started!</Link>
</li>
</ul>
<Link style={navStyle} to="/createquiz1">
<li>Create your quizbot!</li>
</Link>
<li>
<a href="signin.html" a class="waves-effect waves-light btn">
Sign in
</a>
</li>
</ul>
</div>
</nav>
```
A: I just tried to clean up your code, as there was a Link outside a li element. This should work:
<nav>
<div class="nav-wrapper blue lighten-2">
<a class="brand-logo left">
<img src="/images/logo_small.png"></img>
</a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li>
<a href="teechrworks.html">How teechr works?</a>
</li>
<li>
<a href="aboutus.html">About us</a>
</li>
<li>
<Link to="/chooseachatbottype">Get started!</Link>
</li>
<li>
<Link style={navStyle} to="/createquiz1">
Create your quizbot!
</Link>
</li>
<li>
<a href="signin.html" a class="waves-effect waves-light btn">
Sign in
</a>
</li>
</ul>
</div>
</nav>
A: pass a prop of target="__blank" should work like in Standart HTML.
Create your Links in const and you have better overview.
Didn't add your Styles...
import React, { Fragment, useEffect } from 'react';
import { Link } from 'react-router-dom';
const Navbar = () => {
const links = (
<Fragment>
<li>
<Link className="link-item" to='/'>Home</Link>
</li>
<li>
<a className="link-item" href="https://www.google.com" target="__blank">External Website</a>
</li>
</Fragment>
)
return (
<Fragment>
<div className="nav-wrapper">
<ul>
{links}
</ul>
</div>
</Fragment>
)
}
export default Navbar;
Your typo:
<a class="brand-logo left">
<img scr="/images/logo_small.png"></img>
</a>
src not scr
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59935483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using xmlhttp.open async instead of sync I am using xml http to read a XML file and then do something with it. It works fine when I use sync, setting it to "false" when using .open().
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",".."+baseRestUrl+restService+"/"+jmxConnection,false);
xmlhttp.send(null);
xmlDoc=xmlhttp.responseXML;
var beanRepArray = xmlDoc.getElementsByTagName("beanRepresentation");
But when I set it to "true", it always says xmlDoc is not defined.
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",".."+baseRestUrl+restService+"/"+jmxConnection,true);
xmlhttp.send(null);
xmlDoc=xmlhttp.responseXML;
var beanRepArray = xmlDoc.getElementsByTagName("beanRepresentation");
How should I fix this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22258721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I make Discord.JS v13 make a role with Administrator permissions? I've seen a bunch of answers on Stack Overflow showing how to make a role with a colour but it doesn't show how to make it with permissions.
Any ideas?
A: You can create a role with permissions using this:
guild.roles.create({
name: 'Super Cool Blue People',
color: 'BLUE',
reason: 'we needed a role for Super Cool People',
permissions: ['ADMINISTRATOR', 'KICK_MEMBERS'],
})
I have added two examples above ADMINISTRATOR and KICK_MEMBERS.
Flag List: https://discord.js.org/#/docs/main/stable/class/Permissions?scrollTo=s-FLAGS
Please note that you're recommended to use Permissions.FLAGS.<FLAG-NAME> instead of hard-coding the permission name.
A: A guild's RoleManager#create takes a parameter of type CreateRoleOptions, which has a property permissions of type PermissionResolvable. Therefore, you can create a role with specific permissions by calling:
guild.roles.create({
permissions: "ADMINISTRATOR"
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68865754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Honeycomb webview flickering jittering My app has a scrollview and a webview inside a LinearLayout.
When the Ads from millenial come in it happens some jittering and some webview parts get white.
I have tried ALL possible parameter combination and nothing works.
Does anyone a better solution or even a explanation?
Notice the blank text in the bottom:
Notice 9 10 11 and 11 sections:
thanks
A: For those having problems with this I have solved it as following -
Compatibility.getCompatibility().setWebSettingsCache(webSettings);
Make sure to implement a Compatibility layer, since following method doesn't work in SDK_INT < 11.
webViewInstance.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
A: I have similar problem with AdMob, which I solved by adding:
android:layer="software"
to the AdView in my xml layout
A: try adding the attribute android:fadingEdge="none" to the ScrollView in your layout.
A: The answer to this was removing millenial ads. It seems that their animation to bring the ad visible was interfering with the webview stuff.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6183688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: DataSource.initialzie() vs createConnection() in typeorm. Which one to use? I just started using TypeORM as my main ORM for my server. I have seen some tutorials where they use createConnection() instead of creating a DataSource object and initializing it.
Are they different? Do they have different use cases?
Thanks.
A: createConnection() is the old way to do it. Since typeorm 0.3.x you should use the DataSource object with DataSource.initialize().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72927473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Removing /n from print after web scraping I'm trying to capture some columns from the following link:
https://es.wiktionary.org/wiki/Wikcionario:Frecuentes-(1-1000)-Subt%C3%ADtulos_de_pel%C3%ADculas
The code I've come up with is as follows:
import requests
wiki_url = "https://es.wiktionary.org/wiki/Wikcionario:Frecuentes-(1-1000)-Subt%C3%ADtulos_de_pel%C3%ADculas"
wiki_texto = requests.get(wiki_url).text
from bs4 import BeautifulSoup
wiki_datos = BeautifulSoup(wiki_texto, "html")
wiki_filas = wiki_datos.findAll("tr")
print(wiki_filas[1])
print("...............................")
wiki_celdas = wiki_datos.findAll("td")
print(wiki_celdas[0:])
fila_1 = wiki_celdas[0:]
info_1 = [elemento.get_text() for elemento in fila_1]
print(fila_1)
print(info_1)
info_1[0] = int(float(info_1[0]))
print(info_1)
print("...............................")
num_or = [int(float(elem.findAll("td")[0].get_text())) for elem in wiki_filas[1:]]
palabras = [elem.findAll("td")[1].get_text() for elem in wiki_filas[1:]]
frecuencia = [elem.findAll("td")[2].get_text() for elem in wiki_filas[1:]]
print(num_or[0:])
print(palabras[0:])
print(frecuencia[0:])
from pandas import DataFrame
tabla = DataFrame([num_or, palabras, frecuencia]).T
tabla.columns = ["Núm. orden", "Palabras", "Frecuencia"]
print(tabla.head())
The problem is that I can't remove the following /n from colums "Palabras" and "Frecuencia":
Any ideas? Thanks in advance.
A: I think, that rstrip() method should help you:
palabras = [elem.findAll("td")[1].get_text().rstrip() for elem in wiki_filas[1:]]
frecuencia = [elem.findAll("td")[2].get_text().rstrip() for elem in wiki_filas[1:]]
You can also use lstrip for left side and strip() method for both sides of string.
edit: this removes all whitespaces.
A: \n is a newline.
You can remove it either with .replace("\n", ""):
palabras = [elem.findAll("td")[1].get_text().replace("\n", "") for elem in wiki_filas[1:]]
frecuencia = [elem.findAll("td")[2].get_text().replace("\n", "") for elem in wiki_filas[1:]]
Alternatively, .strip() removes any surrounding whitespace.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59783960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: can i put the form-login-page html in a library for a webapp? I was trying to create an app with login page authentication. And for the same i added <form-login-page> into the web.xml (as shown below).
I jar'ed the logon.html and logonerror.html , and added them as a library along with the .war webapp file. (under WEB-INF/lib/logon.jar) .
But when I am deploying the app , am getting ERROR 404 , logon.html not found error.
Any pointers to why ? Cant i keep the logon files (htmls,js,css files) in a library ?
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee">
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>MyFilter</filter-class>
<init-param>
<param-name>Domainname</param-name>
<param-value></param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>SecuredResources</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>Default_Role</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>CONF</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/logon.html</form-login-page>
<form-error-page>/logonerror.html</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>Default_Role</role-name>
</security-role>
</web-app>
A: My understanding is that a WAR will only expose the resources contained within its own root file structure. Hence the work-arounds (weblets, Maven config) mentioned in the answers to this question. You could make a custom build script that unpacked the content of logon.jar into your WAR, but I definitely wouldn't recommend that sort of hack. With a little more information concerning why you want to do this someone may be able to provide a better approach.
A: As far as I understand, html files should be placed in a WAR instead of a JAR because those are web resources. JAR file should only contain classes/resources that would be looked up by your web components (e.g. Servlet, JSP) using class loading mechanism.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5163984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Optimizing svg using scour or any other optimizer in Python I have been using scour and it works well.
I would like to use it inside a Python app instead of a cli.
I would like the output to be the same as when I run the following command on CMD:
scour -i input.svg -o output.svgz --enable-viewboxing --enable-id-stripping \
--enable-comment-stripping --shorten-ids --indent=none
Can't find any documentation how to call this function inside a python application
A: In the scour download, there is a testscour.py that you could use to see how you can access scour from within the code instead over the cli.
When I was finally solving my mostly similar scour problem, I did it like this:
from scour import scour
import re
with open(svg_file, 'r') as f
svg = f.read()
scour_options = scour.sanitizeOptions(options=None) # get a clean scour options object
scour_options.remove_metadata = True # change any option you like
clean_svg = scour.scourString(svg, options = scour_options) # use scour
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51507820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Union types with TypeScript and React I want a component to accepts different props based on the value of a given, specific one. Something like the following.
const Button: React.FC<TButton> = ({ href, children, ...rest }) => {
if (href) {
return <a href={href} {...rest}>{children}</a>
}
return <button {...rest}>{children}</button>
}
type TButton = { href: string & IAnchor } | { href: undefined & IButton }
interface IAnchor extends React.AnchorHTMLAttributes<HTMLAnchorElement> {}
interface IButton extends React.ButtonHTMLAttributes<HTMLButtonElement> {}
Thing is, can't figure how to go through this properly. I mean, it seems the conditions aren't being parsed or interpreted correctly.
If you want to have a closer look at the issue, please refer to this StackBlitz.
A: It seems that you essentially try to use discriminated union. But it seems that it is not working with ...rest. So to make it work
*
*Add additional property to both interfaces, say type which will be used as discriminant
interface IAnchor extends React.DetailedHTMLProps<React.AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement> {
type: 'anchor'
href: string
}
interface IButton extends React.ButtonHTMLAttributes<HTMLButtonElement> {
type: 'button'
}
*Accept porps and than destruct them in condition branch
const Button: React.FC<TButton> = (props): JSX.Element => {
if (props.type === 'anchor') {
const { type, href, children, ...rest } = props;
return (
<a href={href} {...rest}>
{children}
</a>
)
}
const { type, children, ...rest } = props;
return <button {...rest}>{children}</button>
}
See working example
A: I took a look at your StackBlitz and was able to approach this using the ts-toolbelt library:
First, let's define your two different possible prop types (all anchor props and all button props), combine them as a strict union and use a type guard to let our React component know when we're using which set of props:
import { Union } from 'ts-toolbelt'
type TButton = Union.Strict<IAnchor | IButton>
interface IAnchor extends React.AnchorHTMLAttributes<HTMLAnchorElement> {}
interface IButton extends React.ButtonHTMLAttributes<HTMLButtonElement> {}
const isAnchor = (props: TButton): props is IAnchor => {
return props.href !== undefined;
}
const isButton = (props: TButton): props is IButton => {
return props.type !== undefined
}
Now, let's write our custom component that can either be a button or an anchor:
const Button: React.FC<TButton> = ({ children, ...props }): JSX.Element => {
if (isAnchor(props)) {
return (
<a href={props.href} {...props}>
{children}
</a>
)
} else if (isButton(props)) {
return <button {...props}>{children}</button>
}
}
You can view it working in this StackBlitz.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57210843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JPA oneToMany with List and JoinTable I am having a Tournament class and a Member class.
Only tournament has members (that is the information that I need) so in the tournament class I have:
@OneToMany(fetch = FetchType.LAZY,
cascade = CascadeType.PERSIST, orphanRemoval=true)
@JoinTable(name = "tournament_players",
joinColumns={@JoinColumn(name="tournament_id", nullable=false)},
inverseJoinColumns={@JoinColumn(name="member_id", nullable=false)})
List<Member> players;
The ids are auto generated integers.
When I have only one tournament everything its ok when I set the members.
If a I add a member already existed in tournament 1 to tournament 2 then I get a constraint violation which is correct from what I have read.
Unique index or primary key violation: "UK_9JMTVNIY5RJ4A9S9XCI40NQGJ_INDEX_9 ON PUBLIC.TOURNAMENT_PLAYERS(TOURNAMENT_ID)
My question is what is the proper solution to my problem?
A: I think what you really need is ManyToMany relationship.
Because in your case, one Tournament can have many Member(s), and Member can follow many Tournament(s).
If you use OneToMany, the JPA provider will check if the Member already has Tournament assigned, and will fail to add if it true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35821240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multiple/same data I try to make condition where i delete data before insert data to prevent multiple data but it didnt work | even the data in table become empty || 'id_lokasi' is my column name in table - database
$factpelanggan4 = DB::connection('clickhouse')
->select("SELECT t.id_tahun, l.id_lokasi, stage.jml_pelanggan
from dim_tahun t
inner join stage_pelanggan stage on t.tahun = stage.years
inner join dim_lokasi l on stage.city_id = l.id_kota
WHERE (stage.country_id = l.id_negara)
ORDER BY t.id_tahun ASC , l.id_lokasi ASC, stage.jml_pelanggan ASC
");
foreach ($factpelanggan4 as $value) {
$tahun_id[] = $value['t.id_tahun'];
$lokasi_id[] = $value['l.id_lokasi'];
$jml[] = $value['stage.jml_pelanggan'];
}
DB::connection('clickhouse')->table('fakta_pelanggan')->where('id_lokasi', $lokasi_id)->delete();
//DB::connection('clickhouse')->table('fakta_pelanggan')->where('id_lokasi', Not Null)->delete();
foreach ($factpelanggan4 as $key => $value) {
$arrayInsert = array(
'id_tahun' => $tahun_id[$key],
'id_lokasi' => $lokasi_id[$key],
'jml_pelanggan' => $jml[$key],
);
DB::connection('clickhouse')->table('fakta_pelanggan')->insert($arrayInsert);
$key++;
}
A: You should avoid deleting if you're just inserting, or deleting then inserting. If something goes wrong, you'd be left with no data similar to a truncate. What you really should be doing is inserting or updating.
You can do this manually, selecting, then either inserting or updating, separately. Or you can use firstOrCreate, firstOrNew, updateOrCreate or similar approaches.
Since you're working on multiple records at once, you might try an upsert for updating/inserting multiple records at once:
https://laravel.com/docs/9.x/eloquent#upsert
$toInsertOrUpdate = [];
foreach ($factpelanggan4 as $key => $value) {
// I don't quite follow your looping logic.
// What you wrote with $key++ after each loop before
// will be completely ignored since each loop overwrites it.
// This is a factored version of what you wrote before.
// Please double check it to make sure it does what you want.
$toInsertOrUpdate[] = [
'id_tahun' => $tahun_id[$key],
'id_lokasi' => $lokasi_id[$key],
'jml_pelanggan' => $jml[$key],
];
}
// these columns together identify duplicate records.
$uniqueIdentifyingColumns = ['id_tahun','id_lokasi','jml_pelanggan'];
// when a duplicate record is found, only these columns will be updated
$columnsToUpdateOnDuplicate = ['id_tahun','id_lokasi','jml_pelanggan'];
$tbl = DB::connection('clickhouse')->table('fakta_pelanggan');
$tbl->upsert(
$toInsertOrUpdate,
$uniqueIdentifyingColumns,
$columnsToUpdateOnDuplicate
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73030603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP sum array values with same keys This is the original main array:
Array
(
[0] => Array
(
[subtotal] => 0.6000
[taxes] => 0.0720
[charged_amount] => 0.6720
[total_discount] => 0.0000
[provinceName] => BC
[store_key] => 1
[store_id] => 5834
[categories] => Array
(
[2] => 0.6000
[4] => 0
[3] => 0
)
)
[1] => Array
(
[subtotal] => 29.8500
[taxes] => 2.3270
[charged_amount] => 20.2370
[total_discount] => 11.9400
[provinceName] => MB
[store_key] => 9
[store_id] => 1022
[categories] => Array
(
[2] => 0
[4] => 29.8500
[3] => 0
)
)
[2] => Array
(
[subtotal] => 0.3000
[taxes] => 0.0390
[charged_amount] => 0.3390
[total_discount] => 0.0000
[provinceName] => NB
[store_key] => 8
[store_id] => 1013
[categories] => Array
(
[2] => 0.3000
[4] => 0
[3] => 0
)
)
[3] => Array
(
[subtotal] => 24.3100
[taxes] => 1.1830
[charged_amount] => 10.2830
[total_discount] => 15.2100
[provinceName] => NL
[store_key] => 4
[store_id] => 3033
[categories] => Array
(
[2] => 24.3100
[4] => 0
[3] => 0
)
)
[4] => Array
(
[subtotal] => 1116.3400
[taxes] => 127.6960
[charged_amount] => 1110.0060
[total_discount] => 134.0300
[provinceName] => ON
[store_key] => 2
[store_id] => 1139
[categories] => Array
(
[2] => 85.7300
[4] => 143.2800
[3] => 887.3300
)
)
[5] => Array
(
[subtotal] => 10.8500
[taxes] => 1.4100
[charged_amount] => 12.2600
[total_discount] => 0.0000
[provinceName] => ON
[store_key] => 5
[store_id] => 1116
[categories] => Array
(
[2] => 10.8500
[4] => 0
[3] => 0
)
)
)
I just need to add the values of the array [categories] with same keys and use it further to print the total, but not getting correct output, can someone help me out to get the desired result:
Desired result
An array with same keys but total of individual array values
Array ( [2] => 0.9000 [4] => 29.8500 [3] => 1.5 )
NOTE: Initial array is dynamic can have n number of key value pair
Thanks
A: The first thing that you need to do is iterate through the outer array. Then, for each row in the outer array, you and to iterate through each entry in the category element. So this means that we have two foreach loops. Inside the inner foreach, we simply set the value for the current index to be the value of the same index on a 'sum' array (if it doesn't already exist), or increment the value of that index if it already exists in the 'sum' array.
<?php
$sumArray = array();
foreach($outerArray as $row)
{
foreach($row["categories"] as $index => $value)
{
$sumArray[$index] = (isset($sumArray[$index]) ? $sumArray[$index] + $value : $value);
}
}
?>
Demo using your example array
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37998850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Final circle: Knights of the Round Table A friend of mine had a job interview. The question he was asked sounded like this:
Is it possible to create a given number of similarly typed objects virtually arranged in a circle such that each of them contains two final references to its left (clockwise) and right (counterclockwise) neighbours?
If this seems too abstract to you, there was a more concrete interpretation. Think about the Knights of the Round Table. Suppose King Arthur considers their union and arrangement at the table constant and inviolable. To express this idea, he created the following simplified model of a Knight at the Table:
public class Knight {
private final String name;
private final Knight leftNeighbour;
private final Knight rightNeighbour;
public final Knight getLeft() {
return leftNeighbour;
}
public final Knight getRight() {
return rightNeighbour;
}
@Override
public final String toString() {
return name;
}
}
Note that all fields are final. Once set, they cannot be changed. The name field here merely illustrates individual properties of each object (there may also be other fields, final or not, but for the sake of simplicity, they are omitted). The primary interest here are the leftNeighbour and rightNeighbour fields. Being final, they "fasten" the circle making its structure immutable yet consisting of individual objects.
There is one problem, however. As you might have noticed, the above class outline lacks very important detail: constructor(s). There must be a place where the final fields are assigned. To create constructor(s) - that was exactly the problem the interviewer proposed to solve - given the desired number of knights and their names in counterclockwise order, you should create corresponding objects and fill their fields. You may create as many constructors as you need and also may use instance initialization blocks and static factory methods, if you like, just don't touch the above lines. There should be at least one public constructor or a static factory method that returns one of the knights created. For example, the verification code below relies on the
public Knight(int knightCount, IntFunction<String> nameGenerator)
constructor, where nameGenerator of type java.util.function.IntFunction<String> is just a function that supplies a knight's name in response to its index. You may use an array of names instead, if you like.
My friend said that this is possible only via reflection - first create objects giving their leftNeighbour and rightNeighbour fields dumb values (e.g. null), then gain access to these fields and assign them meaningful values. But the interviewer said that the use of reflection, for the purpose of solving this problem, is prohibited. My friend concluded that the problem is unsolvable under such conditions. Indeed, to create a Knight, you need to know his neighbours first since it is not possible to assign a final field after exit from a constructor; but for this you need to know the neighbours of these neighbours including that very first Knight that has not yet been created - the chicken or the egg dilemma.
At first, I thought exactly the same. But after some thinking I come to the conclusion that the problem is not as hopeless as it appeared at the beginning. Could you provide a solution? You may use this verification code:
public static void testRoundTable(int size, IntFunction<String> nameGenerator,
boolean printNames) {
Knight k = new Knight(size, nameGenerator);
Knight a = k;
int c = 0;
do {
if (printNames)
System.out.println(a);
c++;
a = a.getRight();
} while (a != k);
if (c != size)
throw new RuntimeException("Wrong knight count: " + c);
if (printNames)
System.out.println();
a = k;
c = 0;
do {
a = a.getLeft();
if (printNames)
System.out.println(a);
c++;
} while (a != k);
if (c != size)
throw new RuntimeException("Wrong knight count: " + c);
if (!printNames)
System.out.println(c + " knights created");
System.out.println();
}
public static void main(String[] args) {
testRoundTable(10, i -> "Knight #" + (i + 1), true);
testRoundTable(20_000_000, i -> "Knight", false);
}
The output should be as follows:
Knight #1
Knight #2
Knight #3
Knight #4
Knight #5
Knight #6
Knight #7
Knight #8
Knight #9
Knight #10
Knight #10
Knight #9
Knight #8
Knight #7
Knight #6
Knight #5
Knight #4
Knight #3
Knight #2
Knight #1
20000000 knights created
Important notes:
*
*Reflection is strongly prohibited. It was either unknown at the time of King Arthur or considered blasphemous.
*The number of knights that you will be requested to create might be limited only by available memory, so be ready to create very large tables (e.g. with 20000000 knights, as above), without causing a stack overflow.
Here's my solution just for two knights:
public Knight(int knightCount, IntFunction<String> nameGenerator) {
name = nameGenerator.apply(0);
Knight other = new Knight(this, nameGenerator.apply(1));
leftNeighbour = other;
rightNeighbour = other;
}
private Knight(Knight mate, String name) {
this.name = name;
leftNeighbour = mate;
rightNeighbour = mate;
}
This idea can be extended to the case of three, four and any other small number of knights. Each knight is responsible for creating the next one:
public Knight(int knightCount, IntFunction<String> nameGenerator) {
name = nameGenerator.apply(0);
Knight other = new Knight(1, knightCount, this, this, nameGenerator);
rightNeighbour = other;
for (int i = 1; i <= knightCount - 2; i++)
other = other.rightNeighbour;
leftNeighbour = other;
}
private Knight(int index, int knightCount, Knight first, Knight previous,
IntFunction<String> nameGenerator) {
name = nameGenerator.apply(index);
leftNeighbour = previous;
if (index == knightCount - 1)
rightNeighbour = first;
else
rightNeighbour = new Knight(index + 1, knightCount, first, this, nameGenerator);
}
However, this implementation becomes increasingly difficult and would surely cause a stack overflow when the count reaches a million or so. On my computer, the "red line" is 5614.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62374603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Repositories links not working yum.conf in CentOS 6 I am running a linux server using RedHat and Centos 6.4
I need to install gcc onto the server, so I have been trying to use yum to install gcc for me, however I seem to have a bit of an issue with installing and updating packages using yum due to the yum.conf file.
If I open my current yum.conf file, I see the following code:
[main]
cachedir=/var/cache/yum
debuglevel=2
logfile=/var/log/yum.log
pkgpolicy=newest
distroverpkg=redhat-release
tolerant=1
exactarch=1
[base]
name=Red Hat Linux $releasever - $basearch - Base
baseurl=http://mirror.dulug.duke.edu/pub/yum-repository/redhat/$releasever/$basearch/
[updates]
name=Red Hat Linux $releasever - Updates
baseurl=http://mirror.dulug.duke.edu/pub/yum-repository/redhat/updates/$releasever/
and whenever I try to run a yum command - for example, "yum update" I get the following errors in my terminal:
[root@SERVER etc]# yum update
Gathering header information file(s) from server(s)
Server: Red Hat Linux 6 - x86_64 - Base
retrygrab() failed for:
http://mirror.dulug.duke.edu/pub/yum-repository/redhat/6/x86_64/headers/header.info
Executing failover method
failover: out of servers to try
Error getting file http://mirror.dulug.duke.edu/pub/yum-repository/redhat/6/x86_64/headers/header.info
[Errno 4] IOError: <urlopen error >
[root@SERVER etc]#
I believe this is due to some old yum mirrors being down, however I cannot find any reference to a proper set of repositories to use in my yum.conf file which would work on CentOS 6.4
The question is: does anybody know where I can find a set of repositories that will work in this scenario? I know that the Yum website is now found at http://yum.baseurl.org/ however I cannot see anything clear with regard to what repositories I should be putting in my yum.conf file..
I am obviously a linux newbie, so if I am missing something important, flame me gently...
A: Looks like you have a mix of CentOS and RedHat bits. Delete whatever you added. CentOS is easy (examples below). For RedHat if you aren't a registered machine you'll want to use the DVD ISO as source (baseurl=file:///media) or maybe attach to a public EPEL.
Here's a CentOS /etc/yum.conf.
[main]
cachedir=/var/cache/yum/$basearch/$releasever
keepcache=0
debuglevel=2
logfile=/var/log/yum.log
exactarch=1
obsoletes=1
gpgcheck=1
plugins=1
installonly_limit=5
bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=yum distroverpkg=centos-release
And then you should have a few repos that already exist in /etc/yum.repos.d (base/debuginfo/media/vault). Hers's /etc/yum.repos.d/CentOS-Base.repo
[base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
#released updates
[updates]
name=CentOS-$releasever - Updates
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
#contrib - packages by Centos Users
[contrib]
name=CentOS-$releasever - Contrib
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=contrib
#baseurl=http://mirror.centos.org/centos/$releasever/contrib/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21851866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement allowed fields mapping with array object in javascript? I have two object one for allowed fields another one for overall response. I need to map overall response with allowed fields. Existing code working fine with object but not works with array object fields. Kindly suggest the better solution to implement field mapping.
let allowedFields = [
"id",
"candidate_id",
"prospect",
"location",
"jobs.id",
"jobs.name"
]
let data = {
"id": 34050740004,
"candidate_id": 30068728004,
"prospect": false,
"applied_at": "2022-06-10T18:00:52.034Z",
"rejected_at": null,
"last_activity_at": "2022-06-10T18:03:05.070Z",
"location": null,
"jobs": [
{
"id": 4354756004,
"name": "E2E Testing",
"email": "manikandanp97@gmail.com"
},
{
"id": 65765,
"name": "E2E consensys",
"email": "mani.raina@gmail.com"
}
]
}
Below code is working fine with objects, but field mapping is not working for array objects.
async function mapAllowedFields(allowedFields, data) {
const response = {}
allowedFields.forEach((loc) => {
const fields = loc.split(".")
let conditionObj = data
let responseObj = response
for (let i = 0; i < fields.length; i++) {
const key = fields[i]
conditionObj = conditionObj?.[key]
if (i === fields.length - 1) {
responseObj[key] = conditionObj
} else if (responseObj[key] === undefined) {
responseObj[key] = {}
}
responseObj = responseObj[key]
}
})
return response
}
Expected results only with allowed fields be like, fields that does not exist in allowed fields array like applied_at, last_activity_at, rejected_at and in jobs array object, email field should be removed from result
let result = {
"id": 34050740004,
"candidate_id": 30068728004,
"prospect": false,
"location": null,
"jobs": [
{
"id": 4354756004,
"name": "E2E Testing",
},
{
"id": 65765,
"name": "E2E consensys",
}
]
}
A: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#syntax
const allowedFields = [
"id",
"candidate_id",
"prospect",
"location",
"jobs",
"name"
];
const txt = [
{
"id": 34050740004,
"candidate_id": 30068728004,
"prospect": false,
"applied_at": "2022-06-10T18:00:52.034Z",
"rejected_at": null,
"last_activity_at": "2022-06-10T18:03:05.070Z",
"location": null,
"jobs": [
{
"id": 4354756004,
"name": "E2E Testing",
"email": "manikandanp97@gmail.com"
},
{
"id": 65765,
"name": "E2E consensys",
"email": "mani.raina@gmail.com"
}
]
},
{
"id": 34050740004,
"candidate_id": 30068728004,
"prospect": false,
"applied_at": "2022-06-10T18:00:52.034Z",
"rejected_at": null,
"last_activity_at": "2022-06-10T18:03:05.070Z",
"location": null,
"jobs": [
{
"id": 4354756004,
"name": "E2E Testing",
"email": "manikandanp97@gmail.com"
},
{
"id": 65765,
"name": "E2E consensys",
"email": "mani.raina@gmail.com"
}
]
}
];
const obj = JSON.stringify(txt, allowedFields);
document.getElementById("demo").innerHTML = JSON.stringify(JSON.parse(obj), null, 4);
<pre id="demo"></pre>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72602791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Incremental build in TFS 2017 - How to build only code that has changed from the last build? We are currently building an incremental build but it is building all the projects in the proj file regardless of if those projects have changed. Is there a way that a script can be written that would pull out only what has changed and checked in or more of an actual incremental build?
When I build a solution, I should only get the changed dlls not all (which includes Microsoft and other 3rd party dlls which are never changed.
TFS 2017 always delivered all files - changed and unchanged, but I need only changed.
I have tried the following but it did not work:
<PropertyGroup>
<SkipClean>true</SkipClean>
<SkipInitializeWorkspace>true</SkipInitializeWorkspace>
<ForceGet>false</ForceGet>
<IncrementalBuild>true</IncrementalBuild>
</PropertyGroup>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59392216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Check if date object is over one year old I would like to see if a date object is over one year old! I don't know how to even compare them due to the leap years etc..
var oldDate = new Date("July 21, 2001 01:15:23");
var todayDate = new Date();
if(???) {
console.log("it has been over one year!");
} else {
console.log("it has not gone one year yet!");
}
A: You could make the check like this
(todayDate - oldDate) / (1000 * 3600 * 24 * 365) > 1
You can see and try it here:
https://jsfiddle.net/rnyxzLc2/
A: This code should handle leap years correctly.
Essentially:
If the difference between the dates' getFullYear() is more than one,
or the difference equals one and todayDate is greater than oldDate after setting their years to be the same,
then there's more than a one-year difference.
var oldDate = new Date("Oct 2, 2014 01:15:23"),
todayDate = new Date(),
y1= oldDate.getFullYear(),
y2= todayDate.getFullYear(),
d1= new Date(oldDate).setFullYear(2000),
d2= new Date(todayDate).setFullYear(2000);
console.log(y2 - y1 > 1 || (y2 - y1 == 1 && d2 > d1));
A: use getFullYear():
fiddle: https://jsfiddle.net/husgce6w/
var oldDate = new Date("July 21, 2001 01:15:23");
var todayDate = new Date();
var thisYear = todayDate.getFullYear();
var thatYear = oldDate.getFullYear();
console.log(todayDate);
console.log(thatYear);
if(thisYear - thatYear > 1) {
console.log("it has been over one year!");
} else {
console.log("it has not gone one year yet!");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32914772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: c++ Observer pattern: Is it a sensible design to make subject to be an observer at the same time? In observer pattern, subject notices a change to observer. But I also need subject to be notified by observer.
I went something like this for the purpose:
//Observer.h
class Subject;
class Observer{
public:
void update(Subject* p_subject);
void Subject_Notify();
private:
Subject* subject;
}
//Subject.h
#include "Observer.h"
class Subject{
public:
void observer_notify()
{
observer->update(this);
}
void update(Observer* observer);
private:
Observer* observer;
}
//Observer.cpp
#include "Observer.h"
#include "Subject.h"
void Observer::update(Subject* p_subject)
{
//do something with p_subject
}
void Observer::Subject_Notify()
{
subject->update(this);
}
The code seems complicated and I am not sure if I am going in the right direction. Is there alternative or is this just ok?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42665740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Primefaces scrollable datatable header alignment I know it is often discussed issue but I didn't find any reasonable solution. I have a datatatable with filtering, sorting, lazy loading and dynamic columns. If I set width of a datatable to 100% and scroll to right, cells don't align to a header. Is some simple solution? I'm using primefaces-5.0.
XHTML:
<p:dataTable
var="rec"
value="#{bean.list}"
selection="#{bean.selectedRow}"
selectionMode="single"
rowKey="#{rec.id}"
resizableColumns="true"
rows="4"
paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
filteredValue="#{bean.filteredList}"
scrollable="true"
style="width: 100%;">
<p:columns value="#{bean.list}"
width="150"
var="column"
sortBy="#{rec[column.property]}"
filterBy="#{rec[column.property]}"
filterMatchMode="contains" >
<f:facet name="header">
<h:outputText value="#{column.header}" />
</f:facet>
<h:outputText value="#{rec[column.property]}" />
</p:columns>
</p:datatable>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24865349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: CMake undefined reference to irrklang I'm trying to link up CMake for a old project, this is the relevant structure:
Project
-build
-src
-res/include/irk
-all the irrklang header files
In my top-level CMakeLists.txt I have:
target_include_directories(${PROJECT_NAME} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/res/include/irk/")
I believe that's all that is needed since IrrKlang is a header-only library as far as I know. When I try to build however, I get this error:
undefined reference to `irrklang::createIrrKlangDevice(irrklang::E_SOUND_OUTPUT_DRIVER, int, char const*, char const*)'
For some reason CMake doesnt pick up on the library and I've no idea why.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69919766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can an iOS app "know" if it's a beta distribution through Apple's Testflight? I'm in the middle of transitioning from TestFlight's native app to Apple's TestFlight through iTunes Connect. My Xcode Project is set up with a beta scheme and a distribution scheme, so I can include a number of debug features in the beta version using a custom flag (lots of #ifndef PROD in the debug code). The beta scheme also has a separate bundle identifier and bundle display name, so that beta and distribution can live side by side on a tester's phone (separate icons, etc).
With Apple's TestFlight, the bundle ID needs to be the same for beta and for distribution. Because of that, I can't include any of the debug features in my current arrangement.
I'm looking for a way around this. One possibility I thought of was to create another app in iTunes Connect solely for testing, but that seems dirty. Is there a conditional or a way to test, in the code, whether the current build is a TestFlight build or a distribution build? Or is there a better way to handle this?
Thanks in advance!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28598343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sign custom JRE for an Java App in macOS Catalina I bundled my java application as an.app. Inside this bundle is a jre, created with jLink. (Contents/Resources/jre/jre_11.../) I now try to sign it with --deep so it signs everything recursively, but it doesn't seem to work. When I try to notarise the app, I get an error, that the bin files and dynamic libraries are not signed.
This is the command I use:
codesign --force --deep --timestamp --entitlements ./sign.entitlements --options runtime --sign "AppleDevIDStuff" ../../../Desktop/Launch.app/
*
*code sign doesn't give me any errors
*command codesign -vvv --deep --strict ../../../Desktop/Launch.app/ says everything is ok
*If I try to sign Contents/Resources/jre/jre_.../bin I get an error, saying this directory is not a valid bundle (which is true)
*Signing the JRE as a directory for itself, outside the app, gives me the same error (Not a valid package)
*jPackage cannot be used, because it produces a different layout for .app, my application needs a specific layout for the contents inside .app.
I didn't find any guide how to sign a custom created JRE and somehow I'm unable to sign this.
So the question is basically: How to sign a custom JRE created with jLink?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60576250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Java: Need to extract a number from a string I have a string containing a number. Something like "Incident #492 - The Title Description".
I need to extract the number from this string.
Tried
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(theString);
String substring =m.group();
By getting an error
java.lang.IllegalStateException: No match found
What am I doing wrong?
What is the correct expression?
I'm sorry for such a simple question, but I searched a lot and still not found how to do this (maybe because it's too late here...)
A: You are getting this exception because you need to call find() on the matcher before accessing groups:
Matcher m = p.matcher(theString);
while (m.find()) {
String substring =m.group();
System.out.println(substring);
}
Demo.
A: There are two things wrong here:
*
*The pattern you're using is not the most ideal for your scenario, it's only checking if a string only contains numbers. Also, since it doesn't contain a group expression, a call to group() is equivalent to calling group(0), which returns the entire string.
*You need to be certain that the matcher has a match before you go calling a group.
Let's start with the regex. Here's what it looks like now.
Debuggex Demo
That will only ever match a string that contains all numbers in it. What you care about is specifically the number in that string, so you want an expression that:
*
*Doesn't care about what's in front of it
*Doesn't care about what's after it
*Only matches on one occurrence of numbers, and captures it in a group
To that, you'd use this expression:
.*?(\\d+).*
Debuggex Demo
The last part is to ensure that the matcher can find a match, and that it gets the correct group. That's accomplished by this:
if (m.matches()) {
String substring = m.group(1);
System.out.println(substring);
}
All together now:
Pattern p = Pattern.compile(".*?(\\d+).*");
final String theString = "Incident #492 - The Title Description";
Matcher m = p.matcher(theString);
if (m.matches()) {
String substring = m.group(1);
System.out.println(substring);
}
A: You need to invoke one of the Matcher methods, like find, matches or lookingAt to actually run the match.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32290862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Selections in D3: how to use parentNode.appendChild? I'd like to deal with overlapping SVG elements in D3.js using this method from StackOverflow.
However, due to the nature of my code, I want to use a D3 selector rather than this to re-add the element to the DOM. My question is: how can I use a D3 selector to get the relevant node?
This is how the original example does it:
this.parentNode.appendChild(this);
This is my attempt, which fails with "Uncaught TypeError: Cannot call method 'appendChild' of undefined":
var thisNode = d3.select("#" + id);
thisNode.parentNode.appendChild(thisNode);
This JSFiddle (adapted from the original example) demonstrates the problem: http://jsfiddle.net/cpcj5/
How is my D3 selection different from the this in the original example? I tried using thisNode.node().parentNode.appendChild(thisNode) but that also failed.
A: The .parentNode method is for a DOM element, not a d3 selection.
To access the DOM element from a d3 selection is a little tricky, and there are often better ways to achieve what you want to do. Regardless, if you have a single element selected, it will be the first and only item within the first item of a d3.selection - i.e. you need to access it like so:
var someIdDOMelement = d3.select("#someid")[0][0];
An edited example of your original using this: http://jsfiddle.net/cpcj5/1/
If you have the id and specifically want to get the DOM element, I'd just go with getElementById:
var someIdDOMElement = document.getElementById("someid")
Looking at d3 documentation for binding events using on, we can see that, within the function you bind, the this variable is the DOM element for the event which was triggered. So, when dealing with event handling in d3, you can just use this to get the DOM element from within a bound function.
But, looking at your code, I think it's easier to stick with the original implementation for re-appending the node using the original javascript methods, and then creating a d3 selection using d3.select on the dom element bound to this. This is how the original code does it: http://jsfiddle.net/cpcj5/3/
If you have any difficulties caused by this, please comment so I can address them.
A: You can also use selection.node() in D3:
var thisNode = d3.select("#" + id);
thisNode.node().parentNode.appendChild(thisNode.node());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16429199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Different behaviour NSAllowsArbitraryLoadsInWebContent IOS 10.1 and 10.2 When loading a certain url in UIWebView in IOS 10.1 it is failing on
Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made"
However the same webview loads fine in iOS 10.2
I can load the url in both 10.1 and 10.2 if I use NSAllowsArbitraryLoads = YES but only in 10.2 with NSAllowsArbitraryLoadsInWebContent = YES
I tested the URL with nscurl --ats-diagnostics and it passes all tests
I think that the issue may have something to do with an ip location validation within the webpage.
Are the differences between 10.1 and 10.2 in the handling of App Transport Security Settings? Are these documented?
---- Edit -----
I managed to resolve my issue by looking at the error in didFailLoadWithError. This told me exactly what the url was that was causing the failure. I added this url to my Exception Domains with NSExceptionRequiresForwardSecrecy=NO (determined using the ats diagnostics)
This fixed my problem but I still would like to understand the differences in the two versions 10.1 & 10.2.
A: Yes, earlier versions of iOS 10 did still enforce the forward secrecy requirement of app transport security in web views even with the NSAllowsArbitraryLoadsInWebContent key. That was a bug, that was fixed by Apple. The problem is that earlier versions of iOS shipped with the bug so you must be able to handle it, which isn't always possible if you don't know all the possible URLs that your Web you could navigate to. This may be part of the reason that Apple has extended their deadline for enabling app transport security and all apps submitted to the App Store.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41346258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Wpf Clickonce deployment I tried to do the clickonce deployment of a simple demo project. The project is deployed but when I click on the RUN button it gives the error that this application can not start and when I try to launch the application It gives the error that this application can not be installed. What wrong I am doing?
A: Usually the log file from a ClickOnce installation tells you what the problem is. I suggest you take a look at that file.
In my experience, it usually is some dependency that's missing.
Here's a useful guide: Troubleshooting Specific Errors in ClickOnce Deployments
If you are using the Google Chrome web browser to launch ClickOnce applications, then take a look at the Chrome Extension for ClickOnce.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9862365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: asp.net website giving errors after upload to server, works fine on local server I have an asp.net website which when i put it up on my college server gave me an error when i retireved the inner text of an xml element and converted it to date which should be selected on the calender control.
The error i recieve is-
String was not recognized as a valid DateTime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: String was not recognized as a valid DateTime.
Source Error:
Line 91: displayEvent.Text += "<b>On-</b>" + node.SelectSingleNode("date").InnerText + "<br />";
Line 92: displayEvent.Text += "<b>Contact Number-</b>" + node.SelectSingleNode("phone").InnerText + "<br />";
Line 93: DateTime dts1 = Convert.ToDateTime(node.SelectSingleNode("date").InnerText);
Line 94: Calendar1.SelectedDate = dts1;
Line 95: latitude = node.SelectSingleNode("latitude").InnerText;
The xml file looks like-
<root1><data><event_name>Christmas Party</event_name><event_desc>The annual christmas bash is happening as planned. This year there is bound to be more excitement.</event_desc><date>12/25/2011</date><phone>111-111-1111</phone><latitude>43.700573</latitude><longitude>-79.296661</longitude></data><data><event_name>New Year Party</event_name><event_desc>Ring in the new year with us, the party is going to be a never before event with a huge celebrity guest line up.</event_desc><date>12/31/2011</date><phone>222-222-2222</phone><latitude>43.728572</latitude><longitude>-79.48669</longitude></data><data><event_name>Jt Birthday</event_name><event_desc>It's jasmeet's birthday. He wanted to get a samsung nexus s, so i should try and buy that for him.</event_desc><date>12/11/2011</date><phone>333-333-3333</phone><latitude>45.515849</latitude><longitude>-73.553417</longitude></data></root1>
Also i am using the latitude and longitude for showing them on a map. It also has problem converting the inner texts of these elements to double
Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: Input string was not in a correct format.
Source Error:
Line 75: {
Line 76: GMap1.reset();
Line 77: GMap1.addGMarker(new GMarker(new GLatLng(Convert.ToDouble(latitude),Convert.ToDouble(longitude))));
Line 78: GMap1.setCenter(new GLatLng(Convert.ToDouble(latitude), Convert.ToDouble(longitude)), 6);
Line 79: displayEvent.Text = " ";
The thing that i am unable to understand is that all of this working absolutely fine on my computer. when i test it on the local server it works fine but on my college server it is giving these errors. Can anybody guide me as to what am i doing wrong here. Other parts of the website are reading from other xml files and they dont throw any exceptions. This is the latest addition of xml reading to the website, everything else works fine.
The method which is used for reading the xml file and conversion-
protected void okButton_Click(object sender, EventArgs e)
{
GMap1.reset();
GMap1.addGMarker(new GMarker(new GLatLng(Convert.ToDouble(latitude),Convert.ToDouble(longitude))));
GMap1.setCenter(new GLatLng(Convert.ToDouble(latitude), Convert.ToDouble(longitude)), 6);
displayEvent.Text = " ";
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("Xml/try.xml"));
XmlNodeList nodeList = doc.SelectNodes("root1/data");
foreach (XmlNode node in nodeList)
{
if (node.SelectSingleNode("event_name").InnerText.Equals(DropDownList1.SelectedValue))
{
latitude = "";
longitude = "";
displayEvent.Text += "<b>Event name-</b>" + node.SelectSingleNode("event_name").InnerText + "<br />";
displayEvent.Text += "<b>Description-</b>" + node.SelectSingleNode("event_desc").InnerText + "<br />";
displayEvent.Text += "<b>On-</b>" + node.SelectSingleNode("date").InnerText + "<br />";
displayEvent.Text += "<b>Contact Number-</b>" + node.SelectSingleNode("phone").InnerText + "<br />";
Calendar1.SelectedDate = Convert.ToDateTime(node.SelectSingleNode("date").InnerText);
latitude = node.SelectSingleNode("latitude").InnerText;
longitude = node.SelectSingleNode("longitude").InnerText;
}
}
}
A: The two computers have different regional settings. You are converting string "12/25/2011" to a DateTime value. If in Control Panel/Regional Settings short date format is dd/MM/yyyy, then 25 is interpreted as month number and the string is considered invalid, since we only have twelve. As for longitude/latitude values, my guess would be that decimal separator is set to comma on your college server. Consider using the versions of Convert.ToDateTime/ToDouble with the second IFromatProvider parameter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8380850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I replace signed-in user using an older user uid in FireStore Anonymous Login? In my app, users are signed in anonymously. If someone uninstalls the app and re-installs it, the new generated uid is different from the older one. Is there some way I can revert the firebase auth instance to use the older uid instead of the new one?
A: Once a user is signed out from Firebase's anonymous authentication provider, there is no way to reclaim that UID through that provider. Given that a user doesn't have to provide any credentials to sign-in anonymously, allowing them to claim a specific UID would be a big security risk.
The only option would be to build your own provider for Firebase Authentication and give the user the same UID as before there, after you've verified that they are the same user.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69539557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Count the number of occurrences between markers in a python list I have a boolean (numpy) array. And I want to count how many occurrences of 'True' are between the Falses.
Eg for a sample list:
b_List = [T,T,T,F,F,F,F,T,T,T,F,F,T,F]
should produce
ml = [3,3,1]
my initial attempt was to try this snippet:
i = 0
ml = []
for el in b_List:
if (b_List):
i += 1
ml.append(i)
i = 0
But it keeps appending elements in ml for each F in the b_List.
EDIT
Thank you all for your answers. Sadly I can' accept all the answers as correct. I've accepted Akavall's answer because he referred to my initial attempt (I know what I did wrong now) and also did a comparison between the Mark's and Ashwinis posts.
Please don't take as a define answer the accepted solution, since both the other suggestions introduce alternative methods what work equally well
A: itertools.groupby provides one easy way to do this:
>>> import itertools
>>> T, F = True, False
>>> b_List = [T,T,T,F,F,F,F,T,T,T,F,F,T,F]
>>> [len(list(group)) for value, group in itertools.groupby(b_List) if value]
[3, 3, 1]
A: Using NumPy:
>>> import numpy as np
>>> a = np.array([ True, True, True, False, False, False, False, True, True, True, False, False, True, False], dtype=bool)
>>> np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2]
array([3, 3, 1])
>>> a = np.array([True, False, False, True, True, False, False, True, False])
>>> np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2]
array([1, 2, 1])
Can't say that this is the best NumPy solution, but it is still faster than itertools.groupby:
>>> lis = [ True, True, True, False, False, False, False, True, True, True, False, False, True, False]*1000
>>> a = np.array(lis)
>>> %timeit [len(list(group)) for value, group in groupby(lis) if value]
100 loops, best of 3: 9.58 ms per loop
>>> %timeit np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2]
1000 loops, best of 3: 1.4 ms per loop
>>> lis = [ True, True, True, False, False, False, False, True, True, True, False, False, True, False]*10000
>>> a = np.array(lis)
>>> %timeit [len(list(group)) for value, group in groupby(lis) if value]
1 loops, best of 3: 95.5 ms per loop
>>> %timeit np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2]
100 loops, best of 3: 14.9 ms per loop
As @justhalf and @Mark Dickinson pointed out in comments the above code will not work in some cases, so you need to append False on both ends first:
In [28]: a
Out[28]:
array([ True, True, True, False, False, False, False, True, True,
True, False, False, True, False], dtype=bool)
In [29]: np.diff(np.where(np.diff(np.hstack([False, a, False])))[0])[::2]
Out[29]: array([3, 3, 1])
A: Your original try has some problems:
i = 0
ml = []
for el in b_List:
if (b_List): # b_list is a list and will evaluate to True
# unless you have an empty list, you want if (el)
i += 1
ml.append(i) # even if the above line was correct you still get here
# on every iteration, and you don't want that
i = 0
You probably want something like this:
def count_Trues(b_list):
i = 0
ml = []
prev = False
for el in b_list:
if el:
i += 1
prev = el
else:
if prev is not el:
ml.append(i)
i = 0
prev = el
if el:
ml.append(i)
return m
Result:
>>> T, F = True, False
>>> b_List = [T,T,T,F,F,F,F,T,T,T,F,F,T,F]
>>> count_Trues(b_List)
[3, 3, 1]
>>> b_List.extend([T,T])
>>> count_Trues(b_List)
[3, 3, 1, 2]
>>> b_List.extend([F])
>>> count_Trues(b_List)
[3, 3, 1, 2]
This solution runs surprisingly fast:
In [5]: T, F = True, False
In [6]: b_List = [T,T,T,F,F,F,F,T,T,T,F,F,T,F]
In [7]: new_b_List = b_List * 100
In [8]: import numpy as np
# Ashwini Chaudhary's Solution
In [9]: %timeit np.diff(np.insert(np.where(np.diff(new_b_List)==1)[0]+1, 0, 0))[::2]
1000 loops, best of 3: 299 us per loop
In [11]: %timeit count_Trues(new_b_List)
1000 loops, best of 3: 130 us per loop
In [12]: new_b_List = b_List * 1000
# Ashwini Chaudhary's Solution
In [13]: %timeit np.diff(np.insert(np.where(np.diff(new_b_List)==1)[0]+1, 0, 0))[::2]
100 loops, best of 3: 2.25 ms per loop
In [14]: %timeit count_Trues(new_b_List)
100 loops, best of 3: 1.33 ms per loop
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20383692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Use process.on('uncaughtException to show a 500 error page I'm developing an express app.
I currently have the following in my server.js
process.on('uncaughtException', function (err) {
console.log( "UNCAUGHT EXCEPTION " );
console.log( "[Inside 'uncaughtException' event] " + err.stack || err.message );
});
Which stops the server crashing every time there's an error, however, it just sits there...
is it possible to instead of console.log, to send a 500 error page with the error details?
A: I don't think you can from within the uncaughtException do a response since that could happen even when there is no request occurring.
Express itself provides a way to handle errors within routes, like so:
app.error(function(err, req, res, next){
//check error information and respond accordingly
});
A: Per ExpressJS Error Handling, add app.use(function(err, req, res, next){ // your logic }); below your other app.use statements.
Example:
app.use(function(err, req, res, next){
console.log(err.stack);
// additional logic, like emailing OPS staff w/ stack trace
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10221309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Converting a simple regex line from perl to python I am trying to convert this line from Perl to python:
$line =~ s/$alwayssep/ $& /g;
Any ideas how this might be done in python?
A: In Python, do the following where alwayssep is the expression and line is the passed string:
line = re.sub(alwayssep, r' \g<0> ', line)
A: My Pythonizer converts that to this:
line = re.sub(re.compile(alwayssep),r' \g<0> ',line,count=0)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29581638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Password encryption at client side
Possible Duplicate:
About password hashing system on client side
I have to secure the passwords of my web site users. What I did was use MD5 encryption hashing in server side. But the problem is the passwords remain in plain text until it arrives at the server, which means that the password can be captured using traffic monitoring. So what I want is to use a client side password encryption/hashing mechanism and send the encrypted/hashed password.
Can anybody tell what is the way to do this?
A: You've tagged this question with the ssl tag, and SSL is the answer. Curious.
A: I would choose this simple solution.
Summarizing it:
*
*Client "I want to login"
*Server generates a random number #S and sends it to the Client
*Client
*
*reads username and password typed by the user
*calculates the hash of the password, getting h(pw) (which is what is stored in the DB)
*generates another random number #C
*concatenates h(pw) + #S + #C and calculates its hash, call it h(all)
*sends to the server username, #C and h(all)
*Server
*
*retrieves h(pw)' for the specified username, from the DB
*now it has all the elements to calculate h(all'), like Client did
*if h(all) = h(all') then h(pw) = h(pw)', almost certainly
No one can repeat the request to log in as the specified user. #S adds a variable component to the hash, each time (it's fundamental). #C adds additional noise in it.
A: You can also simply use http authentication with Digest (Here some infos if you use Apache httpd, Apache Tomcat, and here an explanation of digest).
With Java, for interesting informations, take a look at :
*
*Understanding Login Authentication
*HTTP Digest Authentication Request & Response Examples
*HTTP Authentication Woes
*Basic Authentication For JSP Page (it's not digest, but I think it's an interesting source)
A: There are MD5 libraries available for javascript. Keep in mind that this solution will not work if you need to support users who do not have javascript available.
The more common solution is to use HTTPS. With HTTPS, SSL encryption is negotiated between your web server and the client, transparently encrypting all traffic.
A: This sort of protection is normally provided by using HTTPS, so that all communication between the web server and the client is encrypted.
The exact instructions on how to achieve this will depend on your web server.
The Apache documentation has a SSL Configuration HOW-TO guide that may be of some help. (thanks to user G. Qyy for the link)
A: This won't be secure, and it's simple to explain why:
If you hash the password on the client side and use that token instead of the password, then an attacker will be unlikely to find out what the password is.
But, the attacker doesn't need to find out what the password is, because your server isn't expecting the password any more - it's expecting the token. And the attacker does know the token because it's being sent over unencrypted HTTP!
Now, it might be possible to hack together some kind of challenge/response form of encryption which means that the same password will produce a different token each request. However, this will require that the password is stored in a decryptable format on the server, something which isn't ideal, but might be a suitable compromise.
And finally, do you really want to require users to have javascript turned on before they can log into your website?
In any case, SSL is neither an expensive or especially difficult to set up solution any more
A: You need a library that can encrypt your input on client side and transfer it to the server in encrypted form.
You can use following libs:
*
*jCryption. Client-Server asymmetric encryption over Javascript
Update after 3 years (2013):
*
*Stanford Javascript Crypto Library
Update after 4 years (2014):
*
*CryptoJS - Easy to use encryption
*ForgeJS - Pretty much covers it all
*OpenPGP.JS - Put the OpenPGP format everywhere - runs in JS so you can use it in your web apps, mobile apps & etc.
A: I've listed a complete JavaScript for creating an MD5 at the bottom but it's really pointless without a secure connection for several reasons.
If you MD5 the password and store that MD5 in your database then the MD5 is the password. People can tell exactly what's in your database. You've essentially just made the password a longer string but it still isn't secure if that's what you're storing in your database.
If you say, "Well I'll MD5 the MD5" you're missing the point. By looking at the network traffic, or looking in your database, I can spoof your website and send it the MD5. Granted this is a lot harder than just reusing a plain text password but it's still a security hole.
Most of all though you can't salt the hash client side without sending the salt over the 'net unencrypted therefore making the salting pointless. Without a salt or with a known salt I can brute force attack the hash and figure out what the password is.
If you are going to do this kind of thing with unencrypted transmissions you need to use a public key/private key encryption technique. The client encrypts using your public key then you decrypt on your end with your private key then you MD5 the password (using a user unique salt) and store it in your database. Here's a JavaScript GPL public/private key library.
Anyway, here is the JavaScript code to create an MD5 client side (not my code):
/**
*
* MD5 (Message-Digest Algorithm)
* http://www.webtoolkit.info/
*
**/
var MD5 = function (string) {
function RotateLeft(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
}
function AddUnsigned(lX,lY) {
var lX4,lY4,lX8,lY8,lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function F(x,y,z) { return (x & y) | ((~x) & z); }
function G(x,y,z) { return (x & z) | (y & (~z)); }
function H(x,y,z) { return (x ^ y ^ z); }
function I(x,y,z) { return (y ^ (x | (~z))); }
function FF(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function GG(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function HH(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function II(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function ConvertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1=lMessageLength + 8;
var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
var lWordArray=Array(lNumberOfWords-1);
var lBytePosition = 0;
var lByteCount = 0;
while ( lByteCount < lMessageLength ) {
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
return lWordArray;
};
function WordToHex(lValue) {
var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
for (lCount = 0;lCount<=3;lCount++) {
lByte = (lValue>>>(lCount*8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
}
return WordToHexValue;
};
function Utf8Encode(string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var x=Array();
var k,AA,BB,CC,DD,a,b,c,d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
string = Utf8Encode(string);
x = ConvertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k=0;k<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=GG(d,a,b,c,x[k+10],S22,0x2441453);
c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=II(a,b,c,d,x[k+0], S41,0xF4292244);
d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=II(c,d,a,b,x[k+6], S43,0xA3014314);
b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
a=AddUnsigned(a,AA);
b=AddUnsigned(b,BB);
c=AddUnsigned(c,CC);
d=AddUnsigned(d,DD);
}
var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
return temp.toLowerCase();
}
A: For a similar situation I used this PKCS #5: Password-Based Cryptography Standard from RSA laboratories. You can avoid storing password, by substituting it with something that can be generated only from the password (in one sentence). There are some JavaScript implementations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4121629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "85"
}
|
Q: block inside interpolation with ruby I'm writing a simple program that asks the user for input for an array and spits out the array and its average. Really easy and I had no issues with it.
In the end I came up with: (in this example I'll just use a random array instead of the code for the user input)
array = [1,2,3]
sum = array.inject(:+)
average = sum.to_f/array.length
puts "The numbers you entered in the array were: #{array.join(" ")}"
puts "The average of those numbers are: #{average}"
The output is expected and gives me:
The numbers you entered in the array were: 1 2 3
The averages of those numbers are: 2.0
However, when I was first trying to code this I was trying to be real slick for an easy assignment and I tried doing an interpolation inside of an interpolation. I utilized this code:
For the fourth line in the above code I used:
puts "The numbers you entered in the array were: #{array.each{|num| print "#{num} "}}"
which outputted:
1 2 3 The numbers you entered in the array were: [1, 2, 3]
So I thought there might have been an issue with doing an interpolation inside a block that was inside of an interpolation.
So I then ran the following code to test for just a block inside interpolation.
puts "The numbers you entered in the array were: #{array.each{|num| print num}}"
which outputted:
123The numbers you entered in the array were: [1, 2, 3]
Can anyone explain the me why the proc is executed inside of the interpolation first, printed and then the puts happens. In addition, why did it puts the array in array.inspect form when I never called .inspect on the array.
A: The question you want answered
When you use variable interpolation, that value to interpolate is going to resolve before the original string.
In this case, your Array.each is doing it's thing and printing out "1" then "2" and finally "3". It returns the original Array of [1, 2, 3]
output> 123 # note new line because we used print
Now that your interpolation is resolved, the rest of the puts finishes up and uses the returned value of [1, 2, 3] and prints:
output> The numbers you entered in the array were: [1, 2, 3]\n
To get the final output of:
output> 123The numbers you entered in the array were: [1, 2, 3]\n
The question everyone WANTS to answer :)
http://www.ruby-doc.org/core-2.1.4/Array.html#method-i-each
When calling Array.each with a block, the return is self.
This is "bad" in your case, because you don't want self returned. It will always return the same thing, your original array.
puts "The numbers you entered in the array were: #{array.each{|num| num*2}}"
The numbers you entered in the array were: [1, 2, 3] # WAT?
As a Sergio Tulentsev said, use .map and .join
puts "The numbers you entered in the array were: #{array.map{|num| num*2}.join(' ')}"
The numbers you entered in the array were: 2 4 6
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26932766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Visual Basic 6 Dynamic Variables I am doing a program using vb6 which is stored datas from mouseclick in term of coordinates. I succeeded doing the first stage which is displaying the clicked coordinates. My problem now is I need to save the coordinate in term of variables so i can call them back to use for another purpose for example to find distance between two points.
if its just two coordinates its easier to find the distance. but when it comes to many coordinates I am stuck. I tried to do an array to stored the data inside loop
1. InputX(ListNum, 0) = Int(x)
2. InputY(ListNum, 1) = Int(y)
3. ListNum=ListNum+1
when I try to call for InputX(2,0) = Text1.Text or Text1.Text=InputX(2,0) none of them working. It seems that the data will be erased after I do a mouseclick
Is there any way which I can set the dynamic variables which stored each my clicked coordinates such as Input1,Input2,Input3 ...InputN
I do this in VB6.
A: The problem you're having is that you're using a two dimensional array there. A two dimensional array looks like a table. That's not what you want though. You want a list of pairs of points. So, create a structure with two integers in it, x and y, and make an array of those structures:
'Right underneath your Class Form1 declaration:
Structure Point
Dim x As Integer
Dim y As Integer
End Structure
Dim length As Integer = 10
Dim Points(length) As Point
'When you want to start using your points put this in the method:
Points(0).x = 10
Points(0).y = 10
Points(1).x = 20
Points(1).y = 40
A: Dynamic variables in VB6
First you declare the variable without giving size:
Dim InputX() As String
Then you give for the first time size to your array using ReDim:
ReDim InputX(5)
If you want to preserve whatever data is already in your array you use ReDim Preserve:
ReDim Preserve InputX(10)
I hope this is what you need.
A: it appears that the first method
Text1.Text=InputX(2,0)
is working. I just need to declare x and y As Single
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4520130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Facebook app in IE - Sometimes getUser() returns 0 although the user already has been connected I using in PHP SDK and sometimes when I'm connecting to my FB app on Internet Explorer the function getUser() returns 0!
Someone knows this weird issue? After some attempts it is getting connected.
It seems that there are cases that facebook doesn't identify the user. Any advice?
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET_KEY,
));
// Get User ID
$fbUserId = number_format($facebook->getUser(), 0, '', '');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9270185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: codeigniter 404_override I have set the $routes['404_override'] = 'city/switch_site'
now in my city controller
class City extends CI_Controller {
function __construct() {
parent::__construct();
}
function switch_site( ) {
$this->load->helper('url'); // load the helper first
$city = $this->uri->segment(1);
$segment_cnt = 1;
$valid_url = '';
switch( $city ) {
case 'pune':
$segments = $this->uri->segment_array(2);
foreach($segments as $value) {
if($segment_cnt > 1) {
$valid_url .= $this->uri->slash_segment($segment_cnt);
}
$segment_cnt++;
}
$this->config->set_item('cityid',1);
$this->config->set_item('cityname','pune');
echo APPPATH.'controllers/'.$valid_url;
include_once(APPPATH.'controllers/'.$valid_url);
break;
case 'mumbai':
$segments = $this->uri->segment_array(2);
foreach($segments as $value) {
if($segment_cnt > 1) {
$valid_url .= $this->uri->slash_segment($segment_cnt);
}
$segment_cnt++;
}
$this->config->set_item('cityid',2);
$this->config->set_item('cityname','mumbai');
include_once(APPPATH.'controllers/'.$valid_url);
break;
default:
}
}
}
how do i now pass the correct url to codeigniter router
A: I think you are going about this all wrong. Inside your switch instead of including other controllers which will not work use the redirect() to take them where they should go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5678848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Any ideas how to create auto-cutting file when it's size overflow some value? I have some primitive logger that writes information to file, but we have memory limitations with sending files to server, is there any practices to auto-cut file when it's size overflow some size value, for example, 2MB?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59734762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to exclude the transparent parts which are not rectangles when conducting Fourier analyses on PNG images? Some PNG images have transparent backgrounds. We can get maps of transparent degree from PNG images through imread.
It's easy to exclude the transparent parts in Fourier analysis if they are rectangles. However, how to exclude the transparent parts which are not rectangles in Fourier analysis (using fft2)?
In this case, how to use the maps of transparent degree in conducting Fourier analysis?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73650177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JQuery: Dialog's current position after moving I got this little problem. I cant get the current position of JQuery after I move it.
Seems like it wont update its position. It just gives the first one.
Another problem I came up with was that the dragStop event wont work either..
A: $('#idOfYourDialog').dialog('widget').position();
use the 'widget' flag to get the ui-dialog (the div that is your dialog) to get it' parameters.
As for the dialog drag-stop - are you binding in the init or through bind? Can you post a code sample?
A: Hmmm... I have this ajax function that calls content from the server. That might be the problem.
I have it like:
$.ajax({
url: href,
success: function(data) {
if(handleAjaxErrors(data)==false) {
openWindowsCount++;
$(data).dialog({
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3340915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement Location Automation Field I am wondering how to go about implementing Location Automation Field, as suggested in this article: http://uxmovement.com/forms/new-form-techniques-proven-to-save-time-and-money/
Are there libraries or services that can help me figure out City/State given the zipcode? I know Google has the Geocoder/decoder or Google Places search that could potentially be useful but their Terms of Use mandate that you must use their services in conjunction with displaying the results on their map, which is a weird thing to do when the user is filling out billing info...
A: Cheers to you for observing TOS. That's good business.
You could use SmartyStreets. LiveAddress API supports city/state and ZIP code lookups. It now has auto-complete as you type an address, too.
I work at SmartyStreets. In fact, we developed the jQuery plugin which does address validation and auto-complete for you. It even supports freeform address fields.
Related question by yours truly, over on UX stack exchange: https://ux.stackexchange.com/questions/22196/combining-all-the-address-fields-into-one
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14757665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Swype gesture on scrollable area I'm trying to add swype support to my winjs applicaiton. It works great as long as the content has no scroll area. However as soon as the content overflows the page, the swype gestures don't work anymore.
If I set body { overflow-y: auto; } to hidden it works fine, but when there is a scrollbar, the swype gestures are not triggered anymore. Why?
Here is my sample:
<html>
<head>
<meta charset="utf-8" />
<title>PointerInput</title>
<link href="gestures.css" rel="stylesheet" />
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery.touchSwipe.min.js"></script>
<link href="/css/ui-themed.css" rel="stylesheet" />
<link href="/css/default.css" rel="stylesheet" />
<style>
body {
overflow-y: auto;
}
</style>
<script>
$(function () {
$("body").swipe({
swipe: function (event, direction, distance, duration, fingerCount) {
$("#lastswype").text(direction);
}
});
});
</script>
</head>
<body>
<div class="TargetContainer" id="targetContainer">
<h1>Hello world</h1>
<h2>Last swype was: <span id="lastswype"></span></h2>
<div id="longText">
<p>
Lorem ipsum dolor sit amet, usu no illum petentium. Deterruisset definitiones reprehendunt eu mei. Cum falli volutpat at. Diceret splendide sed in. Sint noster deseruisse quo in. Vix nihil iisque dissentias at, harum facilis eu vel.
Pro eu dico decore consul. Ea posse incorrupte eam, ea affert verear dissentiunt eos. Mentitum intellegam at sit, stet repudiandae vel eu, sea error harum postea ut. Quod habeo tibique est an, vivendo salutatus pri an. Per tamquam tacimates in. Ut odio autem semper sed, cum ne quod aeterno praesent.
Ut oblique adversarium vis, et commodo discere eloquentiam eum, impetus tritani detracto ius ea. Ne sea expetenda deterruisset. Ea has populo ornatus feugait, assum voluptua interesset cum et. Mel ad aliquip periculis, ad eam vide altera splendide, alienum explicari ut mel. Qui laoreet tibique expetenda eu.
Mel nullam iuvaret ex, vix te tollit nullam. Illud quaestio reformidans cum et, et alia melius eam. Cum summo malorum ex. An decore nonumy appareat pro, alterum elaboraret concludaturque nec an. Ut vim aperiam oblique delectus. Duo et cibo labitur definiebas, ne affert rationibus sed, fuisset invenire vis ne.
Ad discere dolores accusata vix, aperiam vivendo cu vel, quo id nominavi dignissim temporibus. Nec summo democritum in, porro nominavi appareat nec cu. Similique ullamcorper vim ad, at epicuri phaedrum pri, est no alii facilis definitionem. Possim numquam et duo, quo an partem urbanitas, eu efficiendi scripserit vim. Ius putant dolores at, ut assum delenit definiebas sed. Tamquam fabellas sed at, ad ius quem affert nominavi, id elit oratio accusamus eam. Quando nostrum platonem vim ex, per ut tation nonumy assueverit.
Lorem ipsum dolor sit amet, usu no illum petentium. Deterruisset definitiones reprehendunt eu mei. Cum falli volutpat at. Diceret splendide sed in. Sint noster deseruisse quo in. Vix nihil iisque dissentias at, harum facilis eu vel.
Pro eu dico decore consul. Ea posse incorrupte eam, ea affert verear dissentiunt eos. Mentitum intellegam at sit, stet repudiandae vel eu, sea error harum postea ut. Quod habeo tibique est an, vivendo salutatus pri an. Per tamquam tacimates in. Ut odio autem semper sed, cum ne quod aeterno praesent.
Ut oblique adversarium vis, et commodo discere eloquentiam eum, impetus tritani detracto ius ea. Ne sea expetenda deterruisset. Ea has populo ornatus feugait, assum voluptua interesset cum et. Mel ad aliquip periculis, ad eam vide altera splendide, alienum explicari ut mel. Qui laoreet tibique expetenda eu.
Mel nullam iuvaret ex, vix te tollit nullam. Illud quaestio reformidans cum et, et alia melius eam. Cum summo malorum ex. An decore nonumy appareat pro, alterum elaboraret concludaturque nec an. Ut vim aperiam oblique delectus. Duo et cibo labitur definiebas, ne affert rationibus sed, fuisset invenire vis ne.
Ad discere dolores accusata vix, aperiam vivendo cu vel, quo id nominavi dignissim temporibus. Nec summo democritum in, porro nominavi appareat nec cu. Similique ullamcorper vim ad, at epicuri phaedrum pri, est no alii facilis definitionem. Possim numquam et duo, quo an partem urbanitas, eu efficiendi scripserit vim. Ius putant dolores at, ut assum delenit definiebas sed. Tamquam fabellas sed at, ad ius quem affert nominavi, id elit oratio accusamus eam. Quando nostrum platonem vim ex, per ut tation nonumy assueverit.
</p>
</div>
</div>
</body>
</html>
A: After some research, I found out that when an area has a scrolling area doesn't propergate touch events, if not specified otherwise. For eaxample, if an area has horzontal scrolling, I have to spezify, that vertical touch events are still allowed. This can be done with the touch-action property (http://msdn.microsoft.com/en-us/library/windows/apps/hh767313.aspx ).
This fixes my problem:
<style>
body {
overflow-y: auto;
touch-action: pan-x:
}
</style>
|
{
"language": "la",
"url": "https://stackoverflow.com/questions/24707616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the max possible length of a PID of a process? (64 bit) I have been working on AIX and see some of the process ID's running are 8 long....
I am using the PID as a concatenation with another char* value and am trying to work out what that MAX possible length of a PID if you were looking at it from a "char perspective"?
I have looked at the pid_t structure (for example t.html">http://dvbstreamer.sourceforge.net/api/structPID_t.html) and it has the PID as an INT...
On that note I assume a PID is a "signed int"....in that case what is a signed int's max length?
Thanks for the help
Lynton
A: The size in bytes is system dependent and should simply be queried like this:
unsigned int pidLength = sizeof(pid_t);
Edit: If you're worried about the length decimal representation as in printf("%d", myPID);, I suggest querying that, too. For example, the snprintf function returns the number of characters (without null-termination) it would have written if there were enough space. So you can do:
char tmpChar;
int representationLength = snprintf(&tmpChar, 1, "%d", myPID);
if (representationLength == -1) { handle_error(); }
char *finalString = malloc(representationLength + 1);
snprintf(finalString, representationLength + 1, "%d", myPID);
Maybe snprintf(NULL, 0, "%d", myPID) would work to query the length as well, but the Linux snprintf man page says this:
Concerning the return value of snprintf(), SUSv2 and C99 contradict each other: when snprintf() is called with size=0 then SUSv2 stipulates an unspecified return value less than 1, while C99 allows str to be NULL in this case, and gives the return value (as always) as the number of characters that would have been written in case the output string has been large enough.
A: The maximum number of digits in an 32-bit int is 10.
The maximum number of digits in a 64-bit signed int is 19.
The maximum number of digits in a 64-bit unsigned int is 20.
I don't know if AIX uses 32 or 64 bits, signed or unsigned, for its pid_t.
Edit: it's gotta be signed because fork can return -1.
A: Another approach could be to use (int)log10(pid) + 1. Of course, you might need to include space for a terminating null character, but the above should give you the number of characters needed to represent the value as a string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8090888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Making change recursively: How do I modify my algorithm to print all combinations? I have an algorithm that recursively makes change in the following manner:
public static int makeChange(int amount, int currentCoin) {
//if amount = zero, we are at the bottom of a successful recursion
if (amount == 0){
//return 1 to add this successful solution
return 1;
//check to see if we went too far
}else if(amount < 0){
//don't count this try if we went too far
return 0;
//if we have exhausted our list of coin values
}else if(currentCoin < 0){
return 0;
}else{
int firstWay = makeChange(amount, currentCoin-1);
int secondWay = makeChange(amount - availableCoins[currentCoin], currentCoin);
return firstWay + secondWay;
}
}
However, I'd like to add the capability to store or print each combination as they successfully return. I'm having a bit of a hard time wrapping my head around how to do this. The original algorithm was pretty easy, but now I am frustrated. Any suggestions?
CB
A: Without getting into the specifics of your code, one pattern is to carry a mutable container for your results in the arguments
public static int makeChange(int amount, int currentCoin, List<Integer>results) {
// ....
if (valid_result) {
results.add(result);
makeChange(...);
}
// ....
}
And call the function like this
List<Integer> results = new LinkedList<Integer>();
makeChange(amount, currentCoin, results);
// after makeChange has executed your results are saved in the variable "results"
A: I don't understand logic or purpose of above code but this is how you can have each combination stored and then printed.
public class MakeChange {
private static int[] availableCoins = {
1, 2, 5, 10, 20, 25, 50, 100 };
public static void main(String[] args) {
Collection<CombinationResult> results = makeChange(5, 7);
for (CombinationResult r : results) {
System.out.println(
"firstWay=" + r.getFirstWay() + " : secondWay="
+ r.getSecondWay() + " --- Sum=" + r.getSum());
}
}
public static class CombinationResult {
int firstWay;
int secondWay;
CombinationResult(int firstWay, int secondWay) {
this.firstWay = firstWay;
this.secondWay = secondWay;
}
public int getFirstWay() {
return this.firstWay;
}
public int getSecondWay() {
return this.secondWay;
}
public int getSum() {
return this.firstWay + this.secondWay;
}
public boolean equals(Object o) {
boolean flag = false;
if (o instanceof CombinationResult) {
CombinationResult r = (CombinationResult) o;
flag = this.firstWay == r.firstWay
&& this.secondWay == r.secondWay;
}
return flag;
}
public int hashCode() {
return this.firstWay + this.secondWay;
}
}
public static Collection<CombinationResult> makeChange(
int amount, int currentCoin) {
Collection<CombinationResult> results =
new ArrayList<CombinationResult>();
makeChange(amount, currentCoin, results);
return results;
}
public static int makeChange(int amount, int currentCoin,
Collection<CombinationResult> results) {
// if amount = zero, we are at the bottom of a successful recursion
if (amount == 0) {
// return 1 to add this successful solution
return 1;
// check to see if we went too far
} else if (amount < 0) {
// don't count this try if we went too far
return 0;
// if we have exhausted our list of coin values
} else if (currentCoin < 0) {
return 0;
} else {
int firstWay = makeChange(
amount, currentCoin - 1, results);
int secondWay = makeChange(
amount - availableCoins[currentCoin],
currentCoin, results);
CombinationResult resultEntry = new CombinationResult(
firstWay, secondWay);
results.add(resultEntry);
return firstWay + secondWay;
}
}
}
A: I used the following:
/**
* This is a recursive method that calculates and displays the combinations of the coins included in
* coinAmounts that sum to amountToBeChanged.
*
* @param coinsUsed is a list of each coin used so far in the total. If this branch is successful, we will add another coin on it.
* @param largestCoinUsed is used in the recursion to indicate at which coin we should start trying to add additional ones.
* @param amountSoFar is used in the recursion to indicate what sum we are currently at.
* @param amountToChange is the original amount that we are making change for.
* @return the number of successful attempts that this branch has calculated.
*/private static int change(List<Integer> coinsUsed, Integer currentCoin, Integer amountSoFar, Integer amountToChange)
{
//if last added coin took us to the correct sum, we have a winner!
if (amountSoFar == amountToChange)
{
//output
System.out.print("Change for "+amountToChange+" = ");
//run through the list of coins that we have and display each.
for(Integer count: coinsUsed){
System.out.print(count + " ");
}
System.out.println();
//pass this back to be tallied
return 1;
}
/*
* Check to see if we overshot the amountToBeChanged
*/
if (amountSoFar > amountToChange)
{
//this branch was unsuccessful
return 0;
}
//this holds the sum of the branches that we send below it
int successes=0;
// Pass through each coin to be used
for (Integer coin:coinAmounts)
{
//we only want to work on currentCoin and the coins after it
if (coin >= currentCoin)
{
//copy the list so we can branch from it
List<Integer> copyOfCoinsUsed = new ArrayList<Integer>(coinsUsed);
//add on one of our current coins
copyOfCoinsUsed.add(coin);
//branch and then collect successful attempts
successes += change(copyOfCoinsUsed, coin, amountSoFar + coin, amountToChange);
}
}
//pass back the current
return successes;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2209817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: how to access the value of a symbol when it is referred to by another symbol This is a simple example to show what i mean:
> (def code "(def some-code [1 2 3])")
> (def data (read-string code))
> (def var (eval data))
using println:
> (println var)
;; => #'example.system/some-code
> (println some-code)
;; => [1 2 3]
now that var contains a reference to some-code, how do i retrieve [1 2 3] if i have var? its usage would be somthing like this function:
> (return var) ;=> [1 2 3]
A: One way would be to use var-get
user=> (var-get var)
[1 2 3]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12426574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C++: Passing pointer to template class around in C I'm writing a C wrapper API for my lib.
I generally pass my C++ objects as void* in C. And there are naturally access wrapper function for every object's public function. The C code does not access native C++ class members.
Yesterday, someone mentioned on IRC that I should not pass around pointer to C++ template classes as void* in C because it's dangerous. Is this true? How different are pointers to ordinary C++ classes from pointers to template classes?
Thanks!
A: It's bogus. Templates have no special properties re casting that a normal class wouldn't have. Make sure you always use the appropriate cast and you will be fine.
A: This is unrelated to templates vs. normal classes, but if your class has multiple inheritance you should always start with the same type before casting to void*, and likewise when casting back. The address of a pointer will change based on which parent class the pointer type is.
class ParentA
{
// ...
int datumA;
};
class ParentB
{
// ...
int datumB;
};
class Derived : public ParentA, public ParentB
{
// ...
};
int main()
{
Derived d;
ParentA * ptrA = &d;
ParentB * ptrB = &d;
assert((void*)ptrA == (void*)ptrB); // asserts!
}
A: It is always safe to cast some pointer Foo* onto void* and then restore on the same type Foo*. When inheritance is used however, a special care should be taken. Upcasting/downcasting shouldn't be done through the void* pointer. Consider the following code:
#include <cassert>
class Parent
{
int bar;
};
class Derived : public Parent
{
virtual void foo() { }
};
int main()
{
Derived d;
Derived* ptr_derived = &d;
void *ptr_derived_void = ptr_derived;
Derived* ptr_derived_from_void = (Derived*)ptr_derived_void;
assert(ptr_derived_from_void == ptr_derived); //that's OK
Parent* ptr_parent = ptr_derived; //upcast
Parent* ptr_parent_from_void = (Parent*)ptr_derived_void; //upcast?
assert(ptr_parent_from_void == ptr_parent); //that's not OK
return 0;
}
Also this post shows some problem with casting through void*.
A: A template class instantiated with a classes A and B as template args involves the compiler creating two seperate classes that specifically handle these respective types. In many ways this is like an intelligent strongly typed preprocessor macro. It is not that different to manually copy-pasting two seperate "normal" classes who operate on A and B respectively. So no.
The only way it will be dangerous is if you try to cast what was originally:
MyClass<A>
as
MyClass<B>
if A is not B, since they could have a different memory layout.
A: Pointers are just that: pointers to data. The "type" of a pointer makes no difference to anything really (at compile time), it's just for readability and maintainability of code.
For example:
Foo<a> *x = new Foo<a>();
void *y = (void*)x;
Foo<a> *z = (Foo<a>*)y;
Is perfectly valid and will cause no issues. The only problem when casting pointer types is that you may run into dereferencing issues when you've forgotten what the underlying data-type a pointer is referencing actually is.
If you're passing around void* everywhere, just be careful to maintain type integrity.
Don't do something like:
Foo<a> *x = new Foo<a>();
void *z = (void*)x;
//pass around z for a while, then mistakenly...
Foo<b> *y = (Foo<b>*)z;
By accident!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9876883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to fix fatal error in UICollectionView cell? I have MasterViewController with UICollectionView in storyboard. I use this code for my UICollectionView:
MasterViewController:
class MasterViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, URLSessionDownloadDelegate, SKProductsRequestDelegate, SKStoreProductViewControllerDelegate {
@IBOutlet weak var collectionView: UICollectionView?
fileprivate var currentPage: Int = 0
fileprivate var pageSize: CGSize {
let layout = UPCarouselFlowLayout()
var pageSize = layout.itemSize
pageSize.width += layout.minimumLineSpacing
return pageSize
}
override func viewDidLoad() {
super.viewDidLoad()
self.addCollectionView()
self.setupLayout()
}
func setupLayout(){
let pointEstimator = RelativeLayoutUtilityClass(referenceFrameSize: self.view.frame.size)
self.collectionView?.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
self.collectionView?.topAnchor.constraint(equalTo: self.view.topAnchor, constant: pointEstimator.relativeHeight(multiplier: 0.1754)).isActive = true
self.collectionView?.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
self.collectionView?.heightAnchor.constraint(equalToConstant: pointEstimator.relativeHeight(multiplier: 0.6887)).isActive = true
self.currentPage = 0
}
func addCollectionView(){
let pointEstimator = RelativeLayoutUtilityClass(referenceFrameSize: self.view.frame.size)
let layout = UPCarouselFlowLayout()
layout.itemSize = CGSize(width: pointEstimator.relativeWidth(multiplier: 0.73333), height: 400)
layout.scrollDirection = .horizontal
self.collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
self.collectionView?.translatesAutoresizingMaskIntoConstraints = false
self.collectionView?.delegate = self
self.collectionView?.dataSource = self
self.collectionView?.register(MasterViewCell.self, forCellWithReuseIdentifier: "Cell")
let spacingLayout = UPCarouselFlowLayout()
spacingLayout.spacingMode = UPCarouselFlowLayoutSpacingMode.overlap(visibleOffset: 20)
}
MasterViewCell:
class MasterViewCell: UICollectionViewCell {
let customView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 12
return view
}()
var cellImageView: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(self.customView)
self.customView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.customView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
self.customView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1).isActive = true
self.customView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 1).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
RelativeLayoutUtilityClass:
class RelativeLayoutUtilityClass {
var heightFrame: CGFloat?
var widthFrame: CGFloat?
init(referenceFrameSize: CGSize){
heightFrame = referenceFrameSize.height
widthFrame = referenceFrameSize.width
}
func relativeHeight(multiplier: CGFloat) -> CGFloat{
return multiplier * self.heightFrame!
}
func relativeWidth(multiplier: CGFloat) -> CGFloat{
return multiplier * self.widthFrame!
}
But I have this error in MasterViewCell: *Thread 1: Fatal error: init(coder:) has not been implemented*
How to fix it?
A: You haven't implemented the init(coder:) initialiser, as you can see here:
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
You seem to be loading some cells from the storyboard, so you must not just use fatalError here.
The implementation should be quite simple. You can just do the same thing as what you do in the init(frame:) initialiser:
class MasterViewCell: UICollectionViewCell {
let customView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 12
return view
}()
var cellImageView: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.addSubview(self.customView)
self.customView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.customView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
self.customView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1).isActive = true
self.customView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 1).isActive = true
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56826356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Widgets not displaying properly in design view? I am learning Android Studio for the first time and I'm stuck trying to run a program on a physical android device. The problem I'm having is that none of my content (widgets, textview, buttons) appear on the screen on my device. Is there something wrong with the computer I'm using? I can see and manipulate widgets in the editor but a lot of the things on screen I create don't show up in the correct spot except on the blueprint.
I've attached images of everything so you guys can take a look. I'm running this on an AMD A10- 9600p Radeon R5.
Thanks for the help.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="MissingConstraints">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView2"
tools:ignore="UnknownId"
tools:layout_editor_absoluteY="42dp"
android:layout_marginStart="16dp"
app:layout_constraintLeft_toLeftOf="@+id/constraintLayout"
android:layout_marginLeft="16dp" />
<EditText
android:layout_width="0dp"
android:layout_height="0dp"
android:inputType="textMultiLine"
android:ems="10"
android:id="@+id/editText"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="@+id/textView2"
android:layout_marginStart="16dp"
app:layout_constraintLeft_toRightOf="@+id/textView2"
android:layout_marginLeft="16dp"
tools:ignore="UnknownId"
android:text="Hello this is my first app and I have no clue what I'm doing! Hopefully this all works out! I just need a bunch of words so i can create scorolling i am just typing things as fast as i can its problaly mispselled but who realy gives a hooot! just like the pokemon. this comupuete is decent but the bang for the buck is where its at. I caould make raps for fday s but its ok oops i guess i need some more word so this lovely app can scroll like a bouss hog out of the kitchen i think ill go get some ice cream soon yes great idea mr culver holla at ur boy yes"
app:layout_constraintBottom_toTopOf="@+id/button3"
android:layout_marginBottom="16dp"
app:layout_constraintHorizontal_bias="0.75"
app:layout_constraintVertical_bias="0.8"
android:layout_marginEnd="16dp"
app:layout_constraintRight_toRightOf="@+id/constraintLayout"
android:layout_marginRight="16dp" />
<Button
android:text="CANCEL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
tools:ignore="UnknownId"
tools:layout_editor_absoluteY="436dp"
tools:layout_editor_absoluteX="268dp" />
<Button
android:text="OK"
android:layout_width="88dp"
android:layout_height="48dp"
android:id="@+id/button3"
app:layout_constraintRight_toLeftOf="@+id/button2"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
tools:ignore="UnknownId"
app:layout_constraintBaseline_toBaselineOf="@+id/button2" />
</android.support.constraint.ConstraintLayout>
Image from Android Device
Android Studio Screenshot
A: It seems that a lot of your widgets actually do not have constraints. Remove the tools:ignore="MissingConstraints" attribute to see the missing ones. Every widget needs to be constrained at least with two constraints (one for the vertical axis, one for the horizontal axis).
Things display correctly in the layout editor simply because it's much nicer to keep the widgets where you put them while you are designing things, even if they don't have constraints. But on device, those fixed positions are not used.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40078793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Android Studio - Global search not working properly after Arctic Fox update After I updated to the Arctic fox update the global search function started behaving weirdly. (I am referring to the double shift search)
*
*The sorting of the results is very annoying. In the All tab it shows class variables and xml files first instead of classes. Previously it showed classes first and then everything else.
*It does not find results for things I misspell while previously it did an excellent job at that.
Is there any way to fix this behavior?
(I know I can click on the Classes tab to only see classes but that is one extra step that I don't want to do EVERY time I search for something which is about 300 times per day)
A: Click on the Filtering icon at the top right corner of the global search dialog. It seems it remembers the filters.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69531146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why Error when code imap_body or imap_fetchbody and try save attachment in php This is my PHP code:
<?php
$host = 'xxxxx.com';
$username = 'xxxxx@ies-nusantara.com';
$password = 'xxxxxx';
/* try to connect */
$inbox = imap_open("{".$host."/pop3/novalidate- cert}INBOX",$username,$password) or die('Cannot connect to sERVER: ' . imap_last_error());
$emails = imap_search($inbox,'ALL');
if($emails)
{
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number)
{
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
/* output the email header information */
$output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
$output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
$output.= '<span class="from">'.$overview[0]->from.'</span>';
$output.= '<span class="date">on '.$overview[0]->date.'</span>';
$output.= '</div>';
$body = imap_fetchbody($overview[0]->msgno,1.2);
$output.= '<div class="body">'.$body.'</div>';
}
echo $output;
}
How to read body email and save attachment email,
i tried use function imap_fetchbody but error..
Please help me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31855960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: custom ArrayAdapter ViewHolder : imageView changes for several items in Listview not for one only ok i encounter a problem with this custom ArrayAdapter
public class AuthorsAdapter extends ArrayAdapter<Entity> {
View row;
static class ViewHolder {
TextView textViewTitle;
TextView textViewEntitySummary;
ImageView imageViewPicture;
}
public AuthorsAdapter(Context context, LinkedList<Entity> entity) {
super(context, 0, entity);
}
@Override
public View getView( final int position, View convertView, final ViewGroup parent) {
row = convertView;
final ViewHolder holder;
if (row == null) {
row = LayoutInflater.from(getContext()).inflate(R.layout.listview_search_author_template, parent, false);
holder = new ViewHolder();
holder.textViewTitle = (TextView) row.findViewById(R.id.textView_TitleTopLeft);
holder.textViewEntitySummary = (TextView) row.findViewById(R.id.textView_EntitySummary);
holder.imageViewPicture = (ImageView) row.findViewById(R.id.imageView_author);
row.setTag(holder);
} else
holder = (ViewHolder) row.getTag();
holder.textViewTitle.setText(getItem(position).getTitle());
if (!getItem(position).getPictureURL().isEmpty())
Picasso.with(getContext()).load(getItem(position).getPictureURL()).into(holder.imageViewPicture);
holder.textViewEntitySummary.setText(getItem(position).getBiography());
holder.imageViewPicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!getItem(position).isImageResized()) {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
getItem(position).setIsImageResized(true);
} else if (getItem(position).isImageResized()) {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
getItem(position).setIsImageResized(false);
} else {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
}
}
});
return row;
}
everything works well expected the imageView onclicklistener :
holder.imageViewPicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!getItem(position).isImageResized()) {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
getItem(position).setIsImageResized(true);
} else if (getItem(position).isImageResized()) {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
getItem(position).setIsImageResized(false);
} else {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
}
}
});
}
i want that the image change it size on click, it work but when i scroll down in my view, random other items in my listView get affected by clicking on first item... and when i come up in my listview the image is not resized anymore (at index where i clicked) any hints to make this working flawlessly?
A: public class AuthorsAdapter extends ArrayAdapter<Entity> {
static class ViewHolder {
TextView textViewTitle;
TextView textViewEntitySummary;
ImageView imageViewPicture;
}
public AuthorsAdapter(Context context, LinkedList<Entity> entity) {
super(context, 0, entity);
}
@Override
public View getView( final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listview_search_author_template, parent, false);
holder = new ViewHolder();
holder.textViewTitle = (TextView) convertView.findViewById(R.id.textView_TitleTopLeft);
holder.textViewEntitySummary = (TextView) convertView.findViewById(R.id.textView_EntitySummary);
holder.imageViewPicture = (ImageView) convertView.findViewById(R.id.imageView_author);
convertView.setTag(holder);
} else{
holder = (ViewHolder) convertView.getTag();
}
if (!getItem(position).isImageResized()) {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
getItem(position).setIsImageResized(true);
} else if (getItem(position).isImageResized()) {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
getItem(position).setIsImageResized(false);
} else {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
}
holder.textViewTitle.setText(getItem(position).getTitle());
if (!getItem(position).getPictureURL().isEmpty())
Picasso.with(getContext()).load(getItem(position).getPictureURL()).into(holder.imageViewPicture);
holder.textViewEntitySummary.setText(getItem(position).getBiography());
holder.imageViewPicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!getItem(position).isImageResized()) {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
getItem(position).setIsImageResized(true);
} else if (getItem(position).isImageResized()) {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
getItem(position).setIsImageResized(false);
} else {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
}
}
});
return convertView;
}
A: ok i found a workaround by referencing the
private LinkedList<Entity> entity;
public AuthorsAdapter(Context context, LinkedList<Entity> entity) {
super(context, 0, entity);
this.entity = entity;
}
in the constructor
then instead of doing like you said :
.... else{
holder = (ViewHolder) convertView.getTag();
}
if (!getItem(position).isImageResized()) {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
getItem(position).setIsImageResized(true);
} else if (getItem(position).isImageResized()) {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
getItem(position).setIsImageResized(false);
} else {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
} .....
ive made an enhanced for loop like this :
.... else{
holder = (ViewHolder) convertView.getTag();
}
for (Entity foo : entity) {
if (!foo.isImageResized()) {
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
25,
25));
} else if (foo.isImageResized())
holder.imageViewPicture.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
} ....
note that i do some changes in my xml layout so now the image is right Under the title :) and i make it match parent to have bigger sized image...
btw thanks a lot for the hint @Ammar aly it really helped me
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30437851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ThreeJS with panorama view First of all, what I want to do is to create a panorama view of a 3D model.
So what I need to do is:
*
*Create the different pictures (Front, Left, Right, Back, Bottom, Top)
*Load the pictures into a box
*Visual it on the browswer
Every step at the moment is working just one step not as I want. The first step is my problem, I don't know how to calibrate or how to place the camera right that I don't see any corners in the panorama view. At the moment I see the box outlines very well.
So my question is: Can anyone tell me how to set the camera to make a good set of different pictures to combine them later to a panorama view?
A: I'm not sure if you're going to use a "real" camera and pictures or 3D renderings, but for rendering you should:
*
*render each side on a square texture
*set X and Y fov to 90deg.
*point the camera exactly along each axis: +X,-X,+Y,-Y,+Z,-Z
This way you should get 6 pictures that work quite well together.
If you want to do this for a "real" pictures, then you'll need some mapping from your distorted images to a cube map. This will depend on your lens, so it's not so easy; I think that professional apps for this task do this by comparing pictures, rather than just math.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22141749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AJAX Post request with PHP7 I have a problem. Early I use PHP 5.3 in my project and all Ajax post requests works great, but now when I migrate on PHP 7 all this request are not working. How to solve this problem.
$.post
(
'http://test.atk/php/get_list.php',
{
list_item: list_item
},
function(list_data){
alert(list_data);
console.log(list_data);
$("list").html(list_data);
}
);
It`s return empty. In PHP I have:
<?php
session_start();
$user_id = $_SESSION['user_id'];
include_once "db.php";
$list_item = $_POST['list_item'];
$user_list = $conn->prepare("SELECT * FROM list WHERE user_id = :user_id AND list_id = :list_id");
$user_list -> bindValue(":user_id" , $user_id);
$user_list -> bindValue("::list_id" , $list_item);
$user_list -> execute() ?>
And error_log and firebug gives me the next message:
Notice: Undefined index: list_item in X:\home\test.atk\www\php\get_list.php on line 6
I think the problem in new PHP 7, may be it has new syntax for ajax variebles? Help me if know how.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41213103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: LINQ group by maxcount I have this table named Projects.
Name Date Hours
p1 1/1/13 1
p1 1/8/13 2
p1 1/9/13 1
p2 1/3/13 5
p2 1/4/13 3
I'd like to aggregate these into some thing like this
p1 Tue 4
p2 Thu 8
I don't know how to get the Max of Count of Date.Weekday part..
So far, I've tried something like this.
Dim qry = From er in Projects
Group er by er.Name Into Max(er.Date.Value.Weekday), Sum(er.Hours)
But this would give me "Wed" on p1 because its higher than "Tue". What I really want is "Tue" because it has more records thatn "Wed"
A: The trick for finding the day with the most entries is to group by day, then sort the groups by the number of entries in each group, then grab the first one.
Dim query = Projects.GroupBy(Function(e) e.Name, Function(name, groupedEntries) New With { _
.Name = name, _
.TopDay = groupedEntries.GroupBy(Function(e) e.[Date].DayOfWeek).OrderByDescending(Function(g) g.Count()).First().Key, _
.TotalHours = groupedEntries.Sum(Function(e) e.Hours) _
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15352619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: accept leading number in input field
<input type="number" name = "search_number" id="search_number" pattern="[0-9]\d*" class="form-control form-control-sm">
when adding number 00107 it takes only 107, is there any solution that it takes 00107 instead of 107 and if we input 107 it take it as 107 I don't want to add default 00 in input because database contain some data that don't contain 00. if anyone has any solution kindly answer me.
A: You can use text box with custom validation. Here isNumberKey only accept the number for each character
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
function show(){
console.log(document.getElementById('test').value)
}
<input id="test" type="text" onkeypress="return isNumberKey(event)"/>
<button type="button" value="show value" onClick="show()">show value</button>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69071002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: The value from a prompt box when ESC is pressed I have this simple function
function Login()
{
var x=prompt("Please enter your name","");
var xmlhttp;
if (window.XMLHttpRequest)
{// Използваните браузъри
xmlhttp=new XMLHttpRequest();
}
else
{// Кой ли ползва тези версии..
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","login.php?u="+x,true);
xmlhttp.send();
}
The problem is when the user decide to exit the prompt box by clicking ESC.Can someone explain to me what exactly happen with the variable x in this case.I get to the conclusion that it get assignied with the value 'null' and by null I mean a string, because when I check with
If(!is_null($u))
my script doesn't work, but if I replace this with
If($u!='null')
then everything works just fine, so could someone explain me what in fact is happening with the prompt box value when you exit it with pressin ESC?
A: x will receive the null value when the user cancels the prompt, so:
var x=prompt("Please enter your name","");
if (x === null) {
// User canceled
}
Live example
A: It returns as if you had clicked cancel.
It is null not as a string ..
alert( prompt('') === null );
will alert true if you press Esc or cancel button
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6224520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mounting Google Drive on Colab I'm trying to mount my drive on Colab using the following code:
from google.colab import drive
drive._mount('/content/drive')
And I'm getting the following error:
298 # Terminate the DriveFS binary before killing bash.
ValueError: mount failed: invalid oauth code
Tried deleting cookies, restarting the session, but nothing seems to work. I am using a few different google accounts, and only one has a Colab Pro subscription.. but this wasn't an issue till today.
Thanks.
A: for the moment the only solution that is working right now is this from this similar question but two months ago:
!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse
from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass
!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}
%cd /content
!mkdir drive
%cd drive
!mkdir MyDrive
%cd ..
%cd ..
!google-drive-ocamlfuse /content/drive/MyDrive
Let's hope the normal way drive.mount will be fixed soon !
A: Here is the solution you can try:
As of new (messed up) update you can not mount using drive._mount anymore (or at least for now). So what you can do is either copy your folder/directory from your other google drive to your current google drive (the account you are log in to colab with) OR you can simply log out from colab and log in with your google account that has the drive you want to mount to
Remember
use drive.mount and not drive._mount after following the above guideline
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70791308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What is the fastest way to compare two sets in Java to get the elements that are in one set and not the other I've two Hashsets here user and docbaseuser
My Code:
Iterator iterator = user.iterator();
while (iterator.hasNext())
{
String isid = (String)iterator.next();
flag = getCount(isid, Docbaseuser);
if(flag == 0)
{
count++;
System.out.println("Unique user found!");
}
}
private int getCount(String isid, Set<String> docbaseuser)
{
// TODO Auto-generated method stub
int flag = 0;
System.out.println("execution reached getcount");
Iterator iterator = docbaseuser.iterator();
while(iterator.hasNext())
{
String id = (String) iterator.next();
if(isid.equalsIgnoreCase(id))
{
System.out.println("MATCH !!!");
flag++;
break;
}
}
return flag;
}
Is there any better way to compare the hashset user with hashset docbaseuser and fetch the elements from user hashsets which are not present in docbaseuser?
Thank you in advance!
A: boolean flag=false;
for(String files:user){
for(String dbu:docbaseuser){
if(files.equalsIgnoreCase(dbu)){
flag=true;
}
}
if(flag){
//user already exists
flag=false;
}
A: I think u can achieve it this way:
public Set<String> fetch (Set<String> here, Set<String> notHere) {
return here.stream()
.filter(h -> !isIn(h, notHere))
.collect(Collectors.toCollection(HashSet::new));
}
private boolean isIn (String s, Set<String> set) {
for (String str : set) {
if (str.equalsIgnoreCase(s)) return true;
}
return false;
}
EDIT: If you don't need equalsIgnoreCase then you can do this:
public Set<String> fetch (Set<String> here, Set<String> notHere) {
return here.stream()
.filter(h -> !notHere.contains(h))
.collect(Collectors.toCollection(HashSet::new));
}
A: If you need a set of all strings in user which are not present in docbaseuser as if you compared one by one using String.equalsIgnoreCase() but want the O(1) complexity of looking up elements in a HashSet or O(log n) complexity of TreeSet beware not to simply convert all strings to upper case or lower case by using String.toUpperCase() or alike. E.g. one might be tempted to use new TreeSet<>(String.CASE_INSENSITIVE_ORDER).
Here is a solution that behaves exactly like comparing strings using String.equalsIgnoreCase() with O(1) complexity at the initial cost of building a HashSet which is used as an index. But depending on context this could be maintained somewhere else and kept in sync with changes to docuserbase contents.
@FunctionalInterface
private static interface CharUnaryOperator {
char applyAsChar(char operand);
}
private static String mapCharacters(String s, CharUnaryOperator mapper) {
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++)
chars[i] = mapper.applyAsChar(chars[i]);
return String.valueOf(chars);
}
private static Set<String> stringsNotPresentInOtherSetIgnoreCase(Set<String> set, Set<String> otherSet) {
Set<String> index = otherSet.stream()
.flatMap(s -> Stream.of(
mapCharacters(s, Character::toUpperCase),
mapCharacters(s, Character::toLowerCase)
))
.collect(Collectors.toCollection(HashSet::new));
return set.stream()
.filter(s -> !index.contains(mapCharacters(s, Character::toUpperCase)))
.filter(s -> !index.contains(mapCharacters(s, Character::toLowerCase)))
.collect(Collectors.toCollection(HashSet::new));
}
private static void test() {
Set<String> user = Stream.of("max", "John", "PETERSSON", "Tommy", "Strauß").collect(Collectors.toSet());
Set<String> docbaseuser = Stream.of("Max", "Petersson", "Steve", "Brad", "Strauss").collect(Collectors.toSet());
Set<String> usersNotInDocbaseuser = stringsNotPresentInOtherSetIgnoreCase(user, docbaseuser);
if (!usersNotInDocbaseuser.equals(Stream.of("John", "Tommy", "Strauß").collect(Collectors.toSet()))) {
System.out.println("Wrong result");
}
}
Paste that code to some class and call test() in order to make sure that the stringsNotPresentInOtherSetIgnoreCase() method works correctly. Pay special attention to the strings Strauß and Strauss which are considered equal when transformed using String.toUpperCase() before:
System.out.println("Strauß".toLowerCase().equals("strauss".toLowerCase()));
System.out.println("Strauß".toUpperCase().equals("strauss".toUpperCase()));
System.out.println("Strauß".equalsIgnoreCase("strauss"));
Result:
false
true
false
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42953461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Saving user textarea contents into browser storage I'd like to make an autosave feature, but without using server storage and flash. What's the preferred cross browser way to save a textarea, then recall it from browser storage? Internet explorer has userdata afaik but what about the others?
A: Either Local Storage or Session Storage (works in IE8 and other browsers).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7771216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Chrome makes two requests to NodeJS server When I make a POST request in Chrome to my NodeJS Fastify server, Chrome's network tab displays one post request:
However, Fastify logs two requests each with a unique request ID:
Now, what is crazy is that when I perform the same request in Firefox, Fastify only logs one request... So is this a Chrome issue or a Fastify/NodeJS one?
Front-end POST request:
const response = await fetch('/api/signupForm', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
foo: bar,
})
}).then(response => response.json()).catch(error => {
...
});
Fastify request:
fastify.post('/signupForm', {
body: {
type: 'object',
required: ['foo'],
properties: {
foo: {
type: 'string'
}
}
},
//Output Serialization
schema: {
response: {
200: {
type: 'object',
properties: {
success: {
type: 'boolean'
}
}
}
}
},
}, async (req, reply) => {
console.log('route started..............................................................');
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63627204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Converting an RGB image to grayscale for a whole dataset in Python enter image description hereI am new to python programming. i have to convert my dataset rgb images to grayscale then have to apply cycleGAN on that dataset.i am using zelda levels dataset.I have no idea how and haven't found many useful things from looking through the internet. If someone could point me in the right direction, so I can figure out how to either change it to a one channel image or grayscale that would be great.
A: remove this red marked line and it should be fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70241792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Cell shows on top of section header I have an UITableView with custom cells and custom headers. When I move one cell upon editing, it pops up on to of the header view.
How can I keep the header view on top of all the cells?
The app uses storyboard, in case that makes a difference.
This is how it looks? https://www.dropbox.com/s/wg8oiar0d9oytux/iOS%20SimulatorScreenSnapz003.mov
This is my code:
[...]
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"ListCell";
ListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
int handleSection = [self sectionToHandle:indexPath.section];
switch (handleSection)
{
case PrivateLists:
{
if (tableView.isEditing && (indexPath.row == self.privateLists.count))
{
cell.textField.text = NSLocalizedString(@"Lägg till ny lista", nil);
cell.textField.enabled = NO;
cell.textField.userInteractionEnabled = NO;
cell.accessoryType = UITableViewCellAccessoryNone;
cell.editingAccessoryView.hidden = YES;
}
else
{
List *list = [self.privateLists objectAtIndex:indexPath.row];
cell.textField.text = list.name;
cell.textField.enabled = YES;
cell.textField.userInteractionEnabled =YES;
cell.backgroundColor = [UIColor clearColor];
cell.onTextEntered = ^(NSString* enteredString){
list.name = enteredString;
UpdateListService *service = [[UpdateListService alloc]initServiceWithList:list];
[service updatelistOnCompletion:
^(BOOL success){
DLog(@"Updated list");
NSIndexPath *newPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
[self.tableView moveRowAtIndexPath:indexPath toIndexPath:newPath];
[self moveListToTop:list.ListId newIndexPath:newPath];
justMovedWithoutSectionUpdate = YES;
}
onError:
^(NSError *error){
[[ActivityIndicator sharedInstance] hide];
[[ErrorHandler sharedInstance]handleError:error fromSender:self];
}];
};
}
}
break;
default:
return 0;
break;
}
return cell;
}
-(UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 22)];
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 21)];
[textLabel setFont:[[AXThemeManager sharedTheme]headerFontWithSize:15.0]];
[textLabel setTextColor:[[AXThemeManager sharedTheme]highlightColor]];
[textLabel setText:@"SECTION TITLE"];
[textLabel setBackgroundColor:[UIColor clearColor]];
UIImageView *backgroundView = [[UIImageView alloc]initWithImage:[AXThemeManager sharedTheme].tableviewSectionHeaderBackgroundImage];
[backgroundView setFrame:view.frame];
[view addSubview:backgroundView];
[view sendSubviewToBack:backgroundView];
[view addSubview:textLabel];
return view;
}
- (float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 22;
}
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 44;
}
[...]
A: It's a bug.
You can quickly solve it by adding, after the line:
[self.tableView moveRowAtIndexPath:indexPath toIndexPath:newPath];
this lines:
UIView *sectionView = [self.tableView headerViewForSection:indexPath.section];
[self.tableView bringSubviewToFront:sectionView];
A: Not a solution but your code has number of issues. Who knows what happens if you fix them ;)
(1) Your cell may be nil after this line:
ListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
It should look like this:
ListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[ListCell alloc] initWithStyle:style
reuseIdentifier:cellIdentifier] autorelease];
}
(2) Two memory leaks in
-(UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section
->>Fix (When you add the label as subview it gets +1 ref).
UILabel *textLabel = [[[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 21)] autorelease];
->>Fix (When you add the view as subview it gets +1 ref).
UIImageView *backgroundView = [[[UIImageView alloc]initWithImage:[AXThemeManager sharedTheme].tableviewSectionHeaderBackgroundImage] autorelease];
(3) Not a defect but this may help you. Try using this instead of [table reloadData]. It allows to animate things nicely and is not such a hardcore way to update the table. I'm sure it is much more lightweight. Alternatively try to look for other "update" methods. Given you don't delete rows in your example, something like [updateRowsFrom:idxFrom to:idxTo] would help.
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0]
withRowAnimation:UITableViewRowAnimationAutomatic];
A: Good news! I was able to fix/workaround your problem in two different ways (see below).
I would say this is certainly an OS bug. What you are doing causes the cell you have moved (using moveRowAtIndexPath:) to be placed above (in front of) the header cell in the z-order.
I was able to repro the problem in OS 5 and 6, with cells that did and didn't have UITextFields, and with the tableView in and out of edit mode (in your video it is in edit mode, I noticed). It also happens even if you are using standard section headers.
Paul, you say in one of your comments:
I solved it badly using a loader and "locking" the table while
preforming a reloadData
I am not sure what you mean by "using a loader and locking the table", but I did determine that calling reloadData after moveRowAtIndexPath: does fix the problem. Is that not something you want to do?
[self.tableView moveRowAtIndexPath:indexPath toIndexPath:newPath];
//[self.tableView reloadData];
// per reply by Umka, below, reloadSections works and is lighter than reloadData:
[self reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
If you dont want to do that, here is another solution that feels a little hacky to me, but seems to work well (iOS 5+):
__weak UITableViewCell* blockCell = cell; // so we can refer to cell in the block below without a retain loop warning.
...
cell.onTextEntered = ^(NSString* sText)
{
// move item in my model
NSIndexPath *newPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
[self.itemNames removeObjectAtIndex:indexPath.row];
[self.itemNames insertObject:sText atIndex:0];
// Then you can move cell to back
[self.tableView moveRowAtIndexPath:indexPath toIndexPath:newPath];
[self.tableView sendSubviewToBack:blockCell]; // a little hacky
// OR per @Lombax, move header to front
UIView *sectionView = [self.tableView headerViewForSection:indexPath.section];
[self.tableView bringSubviewToFront:sectionView];
A: - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
float heightForHeader = 40.0;
if (scrollView.contentOffset.y<=heightForHeader&&scrollView.contentOffset.y>=0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (scrollView.contentOffset.y>=heightForHeader) {
scrollView.contentInset = UIEdgeInsetsMake(-heightForHeader, 0, 0, 0);
}
}
A: What I did to solve this problem was to set the zPosition of the view in the section header.
headerView.layer.zPosition = 1000 //just set a bigger number, it will show on top of all other cells.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13927616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: remove exact match word from a string I would like to remove the word "amp" in the below sentence.
original:
x <- 'come on ***amp*** this just encourages the already rampant mispronunciation of phuket'
What I want:
x <- 'come on this just encourages the already rampant mispronunciation of phuket'
However, if I used gsub, the "amp" in the word of "rampant" will be removed as well which is NOT the case I want. Can I know what function should I use in this case?
> gsub("amp","", x)
[1] "come on this just encourages the already rant mispronunciation of phuket"
A: You can use this regex:
gsub("\\bamp\\b","", x)
# [1] "come on this just encourages the already rampant mispronunciation of phuket"
The \\b means word boundary.
A: You could also split the string into words, and then compare:
x <- 'come on this just encourages the already rampant mispronunciation of phuket'
split_into_words = strsplit(x, ' ')[[1]]
filtered_words = split_into_words[!split_into_words == 'amp']
paste(filtered_words, collapse = ' ')
[1] "come on this just encourages the already rampant mispronunciation of phuket"
A: You could just find the occurrence of "amp" that has a space in front.
> gsub("\\samp", "", x)
## [1] "come on this just encourages the already rampant mispronunciation of phuket"
where \\s means space. This is more readable as
> gsub(" amp", "", x)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23211923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Consumable web service for any device I am developing a project in Layers with C #, and it is required that it has as output a service, to be consumed by different devices. What type of service can be developed so that your operation is optimal in all devices ?. What do you recommend Soap, Web Api or is there any other
A: Try to use ASP.NET Web API.
Check my sample code but I consume it by Web Pages:
Server Side
[HttpPost]
[Route("api/PostMaterialRequest")]
public IHttpActionResult PostMaterialRequest(List<ItemDto> items)
{
try
{
foreach (var i in items)
{
_context.Items.Add(new Item()
{
MaterialId = i.MaterialId,
Description = i.Description,
Unit = i.Unit,
Quantity = i.Quantity,
MaterialRequestId = i.MaterialRequestId
});
_context.SaveChanges();
}
return Ok();
}
catch (Exception)
{
return BadRequest();
}
}
Client-Side
function postItem(materials) {
$.ajax({
contentType: 'application/json',
type: 'POST',
url: '/api/PostMaterialRequest',
data: JSON.stringify(materials),
success: function (data) {
console.log("do something with " + data);
},
failure: function (response) {
console.log('Failed to save.');
}
});
}
Sample of Web API consume by Mobile
I hope, I point you to right direction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54677635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get a file name from string output using regular expression I have output as string out of which I need to parse a specific file name:
>>> a = "Warning: do not enter your password if anyone else has superuser privileges or access to your account. [1] 15:04:16 [SUCCESS] 1.1.1.1 abc330b125.tar.bz2 my-libs.tar.bz2 xyz-notok-0.tar.gz Stderr: Could not create directory '/usr/share/httpd/.ssh'. Failed to add the host to the list of known hosts (/usr/share/httpd/.ssh/known_hosts)."
I tried this, but instead of getting abc330b125.tar.bz2, I am getting bs.tar.bz2:
>>> re.findall(r'.*([abc|xyz\-ok|!my].*.tar.bz2)', a)
['bs.tar.bz2']
Can someone please let me know if I am making any mistake here?
A: I got the answer:
>>> re.findall(r'(?:abc.*\d+.tar.bz2|xyz\-ok.*.tar.bz2)', a)
['abc330b125.tar.bz2']
A: You can use this regex:
re.findall(r"[\w-]+\.tar.bz2",a)
result
# ['abc330b125.tar.bz2', 'my-libs.tar.bz2']
If you want all filenames, you can do it:
re.findall(r"[\w-]+\.tar.(bz2|gz)",a)
result
# ['abc330b125.tar.bz2', 'my-libs.tar.bz2', 'xyz-notok-0.tar.gz' ]
A: You're using "findall," so I assume you want to find all of the tar files. If that's the case, this will work:
re.findall('\S*\.tar\.bz2', a)
['abc330b125.tar.bz2', 'my-libs.tar.bz2']
If you only want to find the ones beginning with "abc," containing only letters and numbers, you could use this:
re.findall('abc\w*\.tar\.bz2', a)
['abc330b125.tar.bz2']
A: I tried to use regex101.com (awesome website for testing regular expressions) to make some tests and it seems that this regular expression :
[a-zA-Z0-9-_]*(.)(tar)(.)(bz2)
captures what you are asking for.
I'm sure you already know, but for anyone who might want a clarification: to capture the actual "." in the string, you need to enclose them in parentheses.
Hope this helps !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46415011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Processing .ELF with multiple headers for ARM Dissembler I'm writing a simple ARM dissembler which takes an ELF file and reverts it back to its ARM instructions.
I'm having an issue with processing the ELF files which contain multiple program headers I have an example .elf file to demonstrate this but I’m unsure where to upload it.
I think the issue is that I'm passing the wrong start address into the Dissemble() function.
Anyone have any thoughts about this?
MAIN.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "elf.h"
void Disassemble(unsigned int *armI, int count, unsigned int startAddress);
void DecodeInstruction(unsigned int instr, unsigned int Address);
void HexToBinary(int *bits, unsigned int hex);
int SignExtend(unsigned int x, int bits);
int Rotate(unsigned int rotatee, int amount);
void PrintASCII(unsigned int instr);
void ProcessSWI(int *bits, unsigned int instr, char *instructionPtr);
void ProcessBranch(int *bits, unsigned int instr, unsigned int currentAddress, char *instructionPtr);
void ProcessDP(int *bits, unsigned int instr, char *instructionPtr);
void ProcessLDR(int *bits, unsigned int instr, char *instructionPtr);
void ProcessMUL (int *bits, unsigned int instr, char *instructionPtr);
void ProcessLDM(int *bits, unsigned int instr, char *instructionPtr);
int main(int argc, const char * argv[])
{
FILE *fp;
ELFHEADER elfhead;
int i;
unsigned int *armInstructions = NULL;
if(argc < 2)
{
fprintf(stderr, "Usage: DisARM <filename>\n");
return 1;
}
/* Open ELF file for binary reading */
if((fp = fopen(argv[1], "rb")) == NULL)
{
fprintf(stderr, "%s\n", argv[1]);
exit(EXIT_FAILURE);
}
/* Read in the header */
fread(&elfhead, 1, sizeof(ELFHEADER), fp);
if(!(elfhead.magic[0] == 0177 && elfhead.magic[1] == 'E' && elfhead.magic[2] == 'L' && elfhead.magic[3] == 'F'))
{
fprintf(stderr, "%s is not an ELF file\n", argv[1]);
return 2;
}
printf("\nFile-type: %d\n",elfhead.filetype);
printf("Arch-type: %d\n",elfhead.archtype);
printf("Entry: %x\n", elfhead.entry);
printf("Prog-Header: %x\n", elfhead.phdrpos);
printf("Prog-Header-count: %d\n", elfhead.phdrcnt);
printf("Section-Header: %x\n", elfhead.shdrpos);
/* Find and read program headers */
ELFPROGHDR *prgHdr[elfhead.phdrcnt];
for(i = 0; i < elfhead.phdrcnt; i++)
{
fseek(fp, elfhead.phdrpos*(i+1), SEEK_SET);
prgHdr[i] = (ELFPROGHDR*)malloc(sizeof(ELFPROGHDR));
if(!prgHdr)
{
fprintf(fp, "Out of Memory\n");
fclose(fp);
return 3;
}
fread(prgHdr[i], 1, sizeof(ELFPROGHDR), fp);
printf("Segment-Offset: %x\n", prgHdr[i]->offset);
printf("File-size: %d\n", prgHdr[i]->filesize);
printf("Align: %d\n", prgHdr[i]->align);
/* allocate memory and read in ARM instructions */
armInstructions = (unsigned int *)malloc(prgHdr[i]->filesize + 3 & ~3);
if(armInstructions == NULL)
{
fclose(fp);
free(prgHdr[elfhead.phdrcnt]);
fprintf(stderr, "Out of Memory\n");
return 3;
}
fseek(fp, prgHdr[i]->offset, SEEK_SET);
fread(armInstructions, 1, prgHdr[i]->filesize, fp);
/* Disassemble */
printf("\nInstructions\n\n");
Disassemble(armInstructions, (prgHdr[i]->filesize + 3 & ~3) /4, prgHdr[i]->virtaddr);
printf("\n");
free(armInstructions);
free(prgHdr[i]);
}
fclose(fp);
return 0;
}
void Disassemble(unsigned int *armI, int count, unsigned int startAddress)
{
int i;
printf("Address Hex ASCII\tDisassembly\n");
printf("=============================================\n");
for(i = 0; i < count; i++)
{
printf("%08X %08X", startAddress + i*4, armI[i]);
DecodeInstruction(armI[i], startAddress + i*4);
printf("\n");
}
}
void DecodeInstruction(unsigned int instr, unsigned int Address)
{
int bits[32];
char instruction[100];
sprintf(instruction, "\0");
HexToBinary(bits, instr);
printf(" ");
PrintASCII(instr);
printf("\t");
if (bits[27] && bits[26] && bits[25] && bits[24])
ProcessSWI(bits, instr, instruction);
else if (bits[27] && !bits[26] && bits[25])
ProcessBranch(bits, instr, Address, instruction);
else if (!bits[27] && bits[26])
{
if (!bits[25])
ProcessLDR(bits, instr, instruction);
else if (bits[4])
strcat(instruction, "Undefined Instruction.");
else if (!bits[4])
ProcessLDR(bits, instr, instruction);
}
else if (bits[27] && !bits[26] && !bits[25])
ProcessLDM(bits, instr, instruction);
else if (!(bits[27] || bits[26] || bits[25] || bits[24] || bits[23] || bits[22]) && (bits[7] && !bits[6] && !bits[5] && bits[4]))
ProcessMUL(bits, instr, instruction);
else if (!bits[27] && !bits[26])
ProcessDP(bits, instr, instruction);
else
strcat(instruction, "Undefined Instruction.");
printf("%s", instruction);
/* DEBUG PRINT BINARY */
/*printf("\t\t");
for(int i=31;i>=0;i--)
{
printf("%d", bits[i]);
}*/
}
int SignExtend(unsigned int x, int bits)
{
int r;
int m = 1U << (bits - 1);
x = x & ((1U << bits) - 1);
r = (x ^ m) - m;
return r;
}
int Rotate(unsigned int rotatee, int amount)
{
unsigned int mask, lo, hi;
mask = (1 << amount) - 1;
lo = rotatee & mask;
hi = rotatee >> amount;
rotatee = (lo << (32 - amount)) | hi;
return rotatee;
}
void HexToBinary(int *bits, unsigned int hex)
{
int i;
for (i = 0; i < 32; i++)
{
bits[i] = (hex >> i) & 1;
}
}
void PrintCCode(unsigned int instr, char *instructionPtr)
{
switch((instr & 0xF0000000) >> 28)
{
case(13): strcat(instructionPtr, "LE"); break;
case(12): strcat(instructionPtr, "GT"); break;
case(11): strcat(instructionPtr, "LT"); break;
case(10): strcat(instructionPtr, "GE"); break;
case(9): strcat(instructionPtr, "LS"); break;
case(8): strcat(instructionPtr, "HI"); break;
case(7): strcat(instructionPtr, "VC"); break;
case(6): strcat(instructionPtr, "VS"); break;
case(5): strcat(instructionPtr, "PL"); break;
case(4): strcat(instructionPtr, "MI"); break;
case(3): strcat(instructionPtr, "CC/LO"); break;
case(2): strcat(instructionPtr, "CS/HS"); break;
case(1): strcat(instructionPtr, "NE"); break;
case(0): strcat(instructionPtr, "EQ"); break;
}
}
void PrintASCII(unsigned int instr)
{
char c[5];
int i;
c[0] = (instr & 0x000000FF);
c[1] = (instr & 0x0000FF00) >> 8;
c[2] = (instr & 0x00FF0000) >> 16;
c[3] = (instr & 0xFF000000) >> 24;
for(i = 0; i < 4; i++)
{
if(isalpha(c[i]) || ispunct(c[i]))
printf("%c", c[i]);
else
printf("*");
}
}
void ProcessSWI(int *bits, unsigned int instr, char *instructionPtr)
{
strcat(instructionPtr, "SWI");
PrintCCode(instr, instructionPtr);
sprintf(instructionPtr + strlen(instructionPtr), "\t%X", instr & 0x00FFFFFF);
}
void ProcessBranch(int *bits, unsigned int instr, unsigned int currentAddress, char *instructionPtr)
{
if ( bits[24] )
strcat(instructionPtr, "BL");
else
strcat(instructionPtr, "B");
PrintCCode(instr, instructionPtr);
sprintf(instructionPtr + strlen(instructionPtr), "\t&%X", (SignExtend((instr & 0x00FFFFFF) << 2, 26)) + currentAddress + 8);
}
void ProcessDP(int *bits, unsigned int instr, char *instructionPtr)
{
int DP = (instr & 0x01E00000) >> 21;
int Rd = (instr & 0x0000F000) >> 12;
int Rn = (instr & 0x000F0000) >> 16;
int Rot = (instr & 0x00000F00) >> 8;
int Op = (instr & 0x000000FF);
int Rm = (instr & 0x0000000F);
int Sh = (instr & 0x00000060) >> 5;
int Shift;
switch(DP)
{
case(15): strcat(instructionPtr, "MVN"); break;
case(14): strcat(instructionPtr, "BIC"); break;
case(13): strcat(instructionPtr, "MOV"); break;
case(12): strcat(instructionPtr, "ORR"); break;
case(11): strcat(instructionPtr, "CMN"); break;
case(10): strcat(instructionPtr, "CMP"); break;
case(9): strcat(instructionPtr, "TEQ"); break;
case(8): strcat(instructionPtr, "TST"); break;
case(7): strcat(instructionPtr, "RSC"); break;
case(6): strcat(instructionPtr, "SBC"); break;
case(5): strcat(instructionPtr, "ADC"); break;
case(4): strcat(instructionPtr, "ADD"); break;
case(3): strcat(instructionPtr, "RSB"); break;
case(2): strcat(instructionPtr, "SUB"); break;
case(1): strcat(instructionPtr, "EOR"); break;
case(0): strcat(instructionPtr, "AND"); break;
}
PrintCCode(instr, instructionPtr);
if (bits[20] && DP != 10 && DP != 11)
strcat(instructionPtr, "S");
if (DP != 11 && DP != 10)
sprintf(instructionPtr + strlen(instructionPtr), "\tR%d, ", Rd);
else
strcat(instructionPtr, "\t");
if (DP != 13 && DP != 15)
sprintf(instructionPtr + strlen(instructionPtr), "R%d, ", Rn);
if (bits[25])
{
if (!(bits[11] || bits[10] || bits[9] || bits[8]))
sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Op);
else
sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Rotate(Op, Rot*2));
}
else
{
if (bits[4])
Shift = (instr & 0x00000F00) >> 8;
else
Shift = (instr & 0x00000F80) >> 7;
sprintf(instructionPtr + strlen(instructionPtr), "R%d", Rm);
if (Shift > 0)
{
switch(Sh)
{
case(3): if(Shift == 0) strcat(instructionPtr, ", RRX"); else strcat(instructionPtr, ", ROR "); break;
case(2): strcat(instructionPtr, ", ASR "); break;
case(1): strcat(instructionPtr, ", LSR "); break;
case(0): strcat(instructionPtr, ", LSL "); break;
}
sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Shift);
}
}
}
void ProcessLDR(int *bits, unsigned int instr, char *instructionPtr)
{
int sourceReg = (instr & 0x0000F000) >> 12;
int baseReg = (instr & 0x000F0000) >> 16;
int Rm = (instr & 0x0000000F);
int immediate = (instr & 0x00000FFF);
int Shift = (instr & 0x00000F80) >> 7;
int Sh = (instr & 0x00000060) >> 5;
if (bits[20])
strcat(instructionPtr, "LDR");
else
strcat(instructionPtr, "STR");
PrintCCode(instr, instructionPtr);
if (bits[22])
strcat(instructionPtr, "B");
sprintf(instructionPtr + strlen(instructionPtr), "\tR%d", sourceReg);
if (bits[24]) // Pre incremented
{
sprintf(instructionPtr + strlen(instructionPtr), ", [R%d", baseReg);
if (bits[25])
sprintf(instructionPtr + strlen(instructionPtr), ", R%d]", Rm);
else
{
if (immediate > 0)
sprintf(instructionPtr + strlen(instructionPtr), ", #%d]", immediate);
else
strcat(instructionPtr, "]");
}
if (bits[21])
strcat(instructionPtr, "!");
}
else // Post incremented
{
if (bits[21])
strcat(instructionPtr, "!");
sprintf(instructionPtr + strlen(instructionPtr), ", [R%d]", baseReg);
if (bits[25])
{
if(bits[23])
sprintf(instructionPtr + strlen(instructionPtr), ", R%d", Rm);
else
sprintf(instructionPtr + strlen(instructionPtr), ", -R%x", Rm);
if (Shift > 0)
{
switch(Sh)
{
case(3): if(Shift == 0) strcat(instructionPtr, ", RRX"); else strcat(instructionPtr, ", ROR "); break;
case(2): strcat(instructionPtr, ", ASR "); break;
case(1): strcat(instructionPtr, ", LSR "); break;
case(0): strcat(instructionPtr, ", LSL "); break;
}
sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Shift*2); //DOUBLED..
}
}
else
{
if (bits[23])
sprintf(instructionPtr + strlen(instructionPtr), ", #&%x", immediate);
else
sprintf(instructionPtr + strlen(instructionPtr), ", #-&%x", immediate);
}
}
}
void ProcessMUL (int *bits, unsigned int instr, char *instructionPtr)
{
int Rd = (instr & 0x000F0000) >> 16;
int Rm = instr & 0x0000000F;
int Rs = (instr & 0x00000F00) >> 8;
int Rn = (instr & 0x0000F000) >> 12;
if (bits[21])
strcat(instructionPtr, "MLA");
else
strcat(instructionPtr, "MUL");
PrintCCode(instr, instructionPtr);
if(bits[20])
strcat(instructionPtr, "S");
sprintf(instructionPtr + strlen(instructionPtr), "\tR%d, R%d, R%d", Rd, Rm, Rs);
if(bits[21])
printf(", R%d", Rn);
}
void ProcessLDM(int *bits, unsigned int instr, char *instructionPtr)
{
char regList[256] = { 0 };
int listState = 0;
int Rn = (instr & 0x000F0000) >> 16;
int i;
if (bits[20])
strcat(instructionPtr, "LDM");
else
strcat(instructionPtr, "STM");
PrintCCode(instr, instructionPtr);
sprintf(instructionPtr + strlen(instructionPtr), "\tR%d", Rn);
if (bits[21])
strcat(instructionPtr, "!");
strcat(instructionPtr, ", ");
strcat(regList, "{");
for (i = 0; i<16; i++)
{
if (bits[i] && !bits[i+1])
{
sprintf(regList + strlen(regList), "R%d, ", i);
listState = 0;
}
else if (bits[i] && bits[i+1] && !listState)
{
sprintf(regList + strlen(regList), "R%d-", i);
listState = 1;
}
}
strcat(regList, "\b\b}");
strcat(instructionPtr, regList);
if(bits[22])
strcat(instructionPtr, "^");
}
elf.h
#ifndef DisARM_elf_h
#define DisARM_elf_h
typedef struct _elfHeader
{
char magic[4];
char class;
char byteorder;
char hversion;
char pad[9];
short filetype;
short archtype;
int fversion;
int entry;
int phdrpos;
int shdrpos;
int flags;
short hdrsize;
short phdrent;
short phdrcnt;
short shdrent;
short shdrcnt;
short strsec;
} ELFHEADER;
typedef struct _elfProgHeader
{
int type;
int offset;
int virtaddr;
int physaddr;
int filesize;
int memsize;
int flags;
int align;
} ELFPROGHDR;
#endif
Any other general constructive criticism and tips are also greatly welcome.
Please let me know if I need to add additional info to help identify the issues.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14377428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Qnamaker API Replace Alteration I have multiple QnA knowledgebases in our Qnamaker. I used QnaMaker API and successfully uploaded alterations data using PUT method
PUT https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/alterations
and I am able retrieve the same using the GET method
GET https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/alterations
But still my bot is not recognizing the alternate keywords. Any thoughts?
Is there any limit on the max number of alternations that we can add.I uploaded around 1000 alternate keyword combinations.
For example:
In my Knowledge Base, here is one example question
What is Variable API?
I want the bot to identify "What is VariableAPI ?" and "What is Variable API" as the same question and respond with the same answer. For this, I uploaded alternations using the Qnamaker API ( PUT) method.
{ "wordAlterations": [
{
"alterations": [
"Variable API",
"VariableAPI"
]
}
] }
Please, anyone, help me understand what I am doing wrong and why my QnAmaker can't identify them as different words
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58941440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making a custom table with columns that are query results What I want to achieve is to make load one of my django models into a table and add some columns where the additional columns are queries based on 2 of the cells in the row.
For example if the Person model has first name and last name, an additional column would be the result of "select top 1 from another_table where fname=fname and lname=lname"
I tried using django-tables2 and here is my code:
#models.py:
from django.db import models
class Person(models.Model):
fname = models.CharField(max_length=10)
lname = models.CharField(max_length=10)
age = models.IntegerField()
def __unicode__(self):
return '%s %s : %i' % (self.fname, self.lname, self.age)
class Map(models.Model):
person = models.ForeignKey(Person)
info = models.CharField(max_length=10)
def __unicode__(self):
return str(self.person)
# views.py
from django.shortcuts import render
from .models import Person
from django_tables2 import RequestConfig
from .models import Person
from .tables import PersonTable
def people(request):
table = PersonTable(Person.objects.all())
RequestConfig(request).configure(table)
return render(request, 'people.html', {'people': table})
#tables.py:
import django_tables2 as tables
from .models import Person
class PersonInfo(tables.Column):
def render(self, value):
return str(value) # <<====== this is later going to be my query
class PersonTable(tables.Table):
info = PersonInfo()
selection = tables.CheckBoxColumn(accessor="pk", orderable=False)
class Meta:
model = Person
There are 3 problems and any help is appreciated:
*
*I've sub-classed PersonInfo from the Column but the info values are blank.
*when made this sample app without the customized table, the table looked fine but now it is not showing the table border/formatting and also the browser indicates that screen.css was successfully loaded so I do not know why it looks like this.
*The checkboxes are successfully displayed but the do not have an id and they have identical names so how can I make them have distinct ids?
A: Below is how I understand your question, and this is how I would go about it:
# models.py
class Person(models.Model):
name = models.CharField(max_length=100)
age = models.IntergerField()
class Info(models.Model):
the_person = models.ForeignKey(Person)
info = models.CharField(max_length=200)
# views.py
# I'm using Class Based Views from Generic Views
class PersonDetail(ListView):
# automatically uses pk of
# model specified below as slug
model = Person
So now in your template, you can have something like this:
# html. Just a rough html below. I hope it gives you the idea. Might not tabulate the data properly, but the point is is to have both model data in templates, then simply use {% for %} loop to list one data in one column or more columns of the table and then whatever model(s) in the other columns.
<table style="width:100%">
<tr>
<td>Name</td>
<td>Age</td>
<td>Info</td>
</tr>
{% for object in object_list %}
<tr>
<td>{{ object.name }}</td>
<td>{{ object.age }}</td>
{% for i in object.the_person.set_all %}
<td>{{ i.info }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
If you're looking to retrieve two models 'Non-ForeignKey-ed' to each other, you can use context object. See here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31060444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: nvidia cuda 7.5 driver in tensorFlow are not properly handled (ubuntu 14.04) After a an install without pb, I am trying the tutorial about GPUs :
I type :
with tf.device('/gpu:0'):
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
print(c)
sess.run(c)
I got :
Tensor("MatMul_1:0", shape=TensorShape([Dimension(2), Dimension(2)]), dtype=float32, device=/gpu:0)
.
Traceback (most recent call last):
File "", line 1, in
File "/home/olivier/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 345, in run
results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)
File "/home/olivier/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 419, in _do_run
e.code)
tensorflow.python.framework.errors.InvalidArgumentError: Cannot assign a device to node 'b_1': Could not satisfy explicit device specification '/gpu:0'
[[Node: b_1 = Constdtype=DT_FLOAT, value=Tensor, _device="/gpu:0"]]
Caused by op u'b_1', defined at:
File "", line 3, in
File "/home/olivier/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/constant_op.py", line 147, in constant
attrs={"value": tensor_value, "dtype": dtype_value}, name=name).outputs[0]
File "/home/olivier/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1710, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/home/olivier/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 988, in init
self._traceback = _extract_stack()
In Torch7, my GPU works normally
A: The binaries published by google need to find libcudart.so.7.0 in the path library , you just need to add it to LD_LIBRARY_PATH by something like
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/home/olivier/digits-2.0/lib/cuda"
that you put in your .bashrc
A: On an optimus laptop (running Manjaro Linux) it's possible to run TensorFlow with cuda acceleration by starting a python console with optirun:
$optirun python
I detailled the way to do it here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33722904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Setting Content-Length header with PHP filesize() gives ERR_SPDY_PROTOCOL_ERROR in Chrome I'm on a shared hosting site, using Apache 2.2.22 and PHP 7.0.27, gzipped output.
Reading a file with PHP and setting the headers with
header("Content-Length: ".filesize($filename));
gives ERR_SPDY_PROTOCOL_ERROR when viewed in Chrome, with the SSL on, works without SSL.
I know that this means that the given length in the header doesn't match with the real length, but why? How can I get the correct length for the header?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49257432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Typescript: Updating generic request function to grab response data - MX / AxiosResponse I am updating my firebase functions to grab data from MX's platform API. I used to grab data via MX's atrium API. Given I am now grabbing an AxiosResponse type, I need to update the generic function used request/process the data. In addition, I do not know typescript/javascript well and am struggling with the correct formatting. I really appreciate the help!
Error:
'Argument of type 'AxiosResponse' is not assignable to parameter of type '{ response: AxiosResponse<any, any>; body: unknown; }'.
Type 'AxiosResponse' is missing the following properties from type '{ response: AxiosResponse<any, any>; body: unknown; }': response, body
'
This is my attempt to update the generic request function but is causing the error:
const getDataFromMXResponse = <T>({
response,
body,
}: {
response: AxiosResponse;
body: T;
}): T => {
const { statusCode = 400 } = response.status;
if (200 <= statusCode && statusCode <= 299) {
body = response.data;
return body;
} else {
throw new Error(response.statusText || "");
}
};
This line of code is calling the actual function:
const listAccountsResponse = await this.mx.listUserAccounts(
mxUserGuid,
1,
100
);
const accounts = getDataFromMXResponse(listAccountsResponse).accounts || [];
This is the original generic request function:
const getDataFromMXResponse = <T>({
response,
body,
}: {
response: IncomingMessage;
body: T;
}): T => {
const { statusCode = 400 } = response;
if (200 <= statusCode && statusCode <= 299) {
return body;
} else {
throw new Error(response.statusMessage || "");
}
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72957635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get compile/build date on Flutter App? I know how to get the version using package_info, but how to get the build timestamp on Runtime both on ios and android?
A: You can use a build shell script that creates/updates a Dart file in lib/... with constants holding the date before running flutter build ....
You then import that file in your code and use it.
A: I'll suggest that you also consider basically rolling your own version of the package_info library which includes all the information you want to get from the platform code. I use the Gradle build files to update some variables on each build, which I then retrieve from Flutter.
Examining the package_info code shows that it is really a fairly simple MethodChannel use case. You could add anything that you can get from the native side.
A: Expanding on Günter Zöchbauer answer...
*
*Create a text file in your source folder and enter the following
#!/bin/sh
var = "final DateTime buildDate =
DateTime.fromMillisecondsSinceEpoch(($(date "+%s000")));"
echo "$var" > lib/build_date.dart
*Save the text file as
build_date_script.sh
*In Android Studio, open Edit Configurations -> Add New Configuration and add a new 'Shell Script'
*Give it a name, such as 'Write build date'
*Select 'Script file' and enter the location of the 'build_date_script.sh' we created it stage 2.
*Download and install GitBash https://gitforwindows.org/
*Back to Android Studio, change the interpreter path to 'C:\Program Files\Git\git-bash.exe'.
*Uncheck 'Execute in terminal' and click 'Apply'
*Then in your main flutter run configuration, add a 'Before launch' item, select 'Run another configuration' and choose the script config we named in stage 4.
*Click OK.
Now every time you build it will create a new dart file in your lib folder called 'build_date.dart' with a variable called 'buildDate' for use as a build date within your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54089645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: ftp_login failing on the second login attempt? I am trying to download a large number of files via FTP. This leads to a strange Warning of
Warning: ftp_get(): Getting data connection.
My solution was just to log out, using ftp_close, and log back in, code is shown below, however, this leads to the warning of
Warning: ftp_login(): User name okay, need password
The thing is I am using the exact same user name and password when I get the previous warning and I have already downloaded dozens of files by this point so the user name and password are correct. I also have the code print the credentials just to confirm that they are the correct ones and that they exist. Has anyone else dealt with this kind of warning combination?
The code I use to login.
//Attempt to connect and login to the server
if (!$this->oFTP = ftp_connect($this->cHost)) {
exit("\n<br>COULD NOT CONNECT TO SERVER: $this->cHost");
} else {
echo "\n<br>CONNECTION SUCESSFUL: $this->cHost";
if(!ftp_login($this->oFTP, $this->cFtpUserName, $this->cFtpUserPass)){
exit("\n<br>LOGIN FAILURE!: $this->cFtpUserName, $this->cFtpUserPass");
} else {
echo "\n<br>LOGIN SUCESSFUL: $this->cFtpUserName";
}
}
//Make sure we are using the correct ip address
ftp_set_option($this->oFTP, FTP_USEPASVADDRESS, false);
//Allows us to retrive files
ftp_pasv($this->oFTP,true);
EDIT:
After some asked about this I looked back of my logs of the connection and it looks like this might not actually be getting any files with ftp_get. I have another script that runs the exact same function with the same login credentials so I know it is working. If that were running at the same time could that be an issue?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59196535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to take an element class, assign them strings from an array and return them as attributes in jQuery? I have a repeated class of .fancybox contained within image maps.
<map name="Map1" id="Map1">
<area shape="rect" coords="609,235,834,335" href="about.html" class="fancybox" rel="iframe" />
<area shape="rect" coords="649,546,807,565" href="info.html" class="fancybox" rel="iframe" />
<area shape="rect" coords="670,566,781,582" href="help.html" class="fancybox" rel="iframe" />
</map>
<map name="Map2" id="Map2">
<area shape="rect" coords="609,235,834,335" href="contact.html" class="fancybox" rel="iframe" />
<area shape="rect" coords="649,546,807,565" href="comments.html" class="fancybox" rel="iframe" />
</map>
I then have an array in jQuery where I want to add the Title attribute. I know it can added in the HTML, but I need it fed by this array clientside as the image maps are generated by the server side CMS that I can't edit.
$(document).ready(function() {
var mapDetails = [
//Map1
"About Page",
"Information",
"Get Help",
//Map2
"Contact Me",
"Post Comments"
];
$('.fancybox').each(function() {
$(this).attr('title', mapDetails[$(this).index()]);
})
});
The problem I have is that on Map2 it starts from the beginning of the array again instead of carrying on in the array as the fourth .fancybox on the page. I'm assuming it's because they have different parent elements. Can I take all the .fancybox elements, assign them the titles from the array and update the HTML with jQuery so that all the .fancybox classes on the page are assigned from the array in order they appear?
I have also tried using the 'area' selector with the same result:
$('area').each(function() {
$(this).attr('title', mapDetails[$(this).index()]);
})
A: Since you're calling index() without arguments, it returns the index of each element relative to its siblings. Therefore, that index will "reset" when going from one <map> element to another.
You can use the index argument provided by each() instead:
$(".fancybox").each(function(index) {
$(this).attr("title", mapDetails[index]);
});
That way, the index will keep incrementing for each element and will not reset between maps.
A: You should use the index of each()
$('.fancybox').each(function(index, el) {
$(this).attr('title', mapDetails[index]);
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9735292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.