Your code was compiled with Java 8.
Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.
Hope this helps...
Im using spring boot 2.1.0
and what worked for me was to
A. Add cors mappings by:
@Configuration
public class Config implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
}
B. Add below configuration to my HttpSecurity
for spring security
.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
return config;
}
})
Also in case of a Zuul proxy you can use this INSTEAD OF A and B (just use HttpSecurity.cors()
to enable it in Spring security):
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
The configuration here is working for me:
configurations {
customProvidedRuntime
}
dependencies {
compile(
// Spring Boot dependencies
)
customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}
war {
classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}
springBoot {
providedConfiguration = "customProvidedRuntime"
}
This may be not the full answer to your question, however if you are looking for way to disable csrf protection you can do:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString())
.anyRequest().permitAll()
.and()
.formLogin().loginPage("/web/login").permitAll()
.and()
.csrf().ignoringAntMatchers("/contact-email")
.and()
.logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("admin").roles(ADMIN.toString())
.and()
.withUser("guest").password("guest").roles(GUEST.toString());
}
}
I have included full configuration but the key line is:
.csrf().ignoringAntMatchers("/contact-email")
Execution is not related to laravel go to the php.ini file In php.ini file set max_execution_time=360 (time may be variable depends on need) if you want to increase execution of a specific page then write ini_set('max_execution_time',360) at top of page
otherwise in htaccess php_value max_execution_time 360
I had same issue using different dependancy what helped me is to set scope to compile.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>compile</scope>
</dependency>
For most use cases, it's not correct to register MultipartFilter in web.xml because Spring MVC already does the work of processing your multipart request. It's even written in the filter's javadoc.
On the server side, define a multipartResolver bean in your app context:
@Bean
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setDefaultEncoding("utf-8");
commonsMultipartResolver.setMaxUploadSize(50000000);
return commonsMultipartResolver;
}
On the client side, here's how to prepare the request for use with Spring RestTemplate API:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
LinkedMultiValueMap<String, String> pdfHeaderMap = new LinkedMultiValueMap<>();
pdfHeaderMap.add("Content-disposition", "form-data; name=filex; filename=" + file.getOriginalFilename());
pdfHeaderMap.add("Content-type", "application/pdf");
HttpEntity<byte[]> doc = new HttpEntity<byte[]>(file.getBytes(), pdfHeaderMap);
LinkedMultiValueMap<String, Object> multipartReqMap = new LinkedMultiValueMap<>();
multipartReqMap.add("filex", doc);
HttpEntity<LinkedMultiValueMap<String, Object>> reqEntity = new HttpEntity<>(multipartReqMap, headers);
ResponseEntity<MyResponse> resE = restTemplate.exchange(uri, HttpMethod.POST, reqEntity, MyResponse.class);
The important thing is really to provide a Content-disposition header using the exact case, and adding name and filename specifiers, otherwise your part will be discarded by the multipart resolver.
Then, your controller method can handle the uploaded file with the following argument:
@RequestParam("filex") MultipartFile file
Hope this helps.
I got this error for a stupid mistake, the variable name in the @PathVariable wasn't matching the one in the @RequestMapping
For example
@RequestMapping(value = "/whatever/{**contentId**}", method = RequestMethod.POST)
public … method(@PathVariable Integer **contentID**){
}
It may help others
I've had this problem and the solution was to use the special magic GUID.
val id: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") // Any other GUID doesn't work.
val device: BluetoothDevice = bta!!.bondedDevices.first { z -> z.name == deviceName }
bts = device.createRfcommSocketToServiceRecord(id) // mPort is -1
bts?.connect()
// Start processing thread.
I suspect that these are the UUIDs that work:
var did: Array<ParcelUuid?> = device.uuids
However, I have not tried them all.
Considering this as a general programming problem, some possible causes are:
The service could be temporarily broken
You could have a problem with a firewall. These could be local or they could be implemented by your ISPs.
Your proxy HTTP settings (if you need one) could be incorrect. This Answer explains how to adjust the Eclipse-internal proxy settings ... if that is where the problem lies.
It is possible that your access may be blocked by over-active antivirus software.
The service could have blacklisted some net range and your hosts IP address is "collateral damage".
Try connecting to that URL with a web browser to try to see if it is just Eclipse that is affected ... or a broader problem.
Considering this in the context of the Eclipse Marketplace service, first address any local proxy / firewall / AV issues, if they apply. If that doesn't help, the best thing that you can do is to be patient.
It has been observed that the Eclipse Marketplace service does sometimes go down. It doesn't happen often, and when it does happen the problem does get fixed relatively quickly. (Hours, not days ...)
I can't find a "service status" page or feed or similar for the Eclipse services. (If you know of one, please add it as a comment below.)
There may be an "outage" notice on the Eclipse front page. Check for that.
Try to connect to the service URL (refer to the exception message!) using a web browser and/or from other locations. If you succeed, the real problem may be a networking issue at your end.
If you feel the need to complain about Eclipse's services, please don't do it here!! (It is off topic.)
You need to make TestGetMethod async
too and attach await in front of GetIdList();
will unwrap the task to List<int>
, So if your helper function is returning Task make sure you have await as you are calling the function async
too.
public Task<List<int>> TestGetMethod()
{
return GetIdList();
}
async Task<List<int>> GetIdList()
{
using (HttpClient proxy = new HttpClient())
{
string response = await proxy.GetStringAsync("www.test.com");
List<int> idList = JsonConvert.DeserializeObject<List<int>>();
return idList;
}
}
Another option
public async void TestGetMethod(List<int> results)
{
results = await GetIdList(); // await will unwrap the List<int>
}
Class that will call the methods:
namespace myNamespace
{
public class myClass
{
public static void voidMethodWithoutParameters()
{
// code here
}
public static string stringReturnMethodWithParameters(string param1, string param2)
{
// code here
return "output";
}
}
}
Calling myClass static methods using Reflection:
var myClassType = Assembly.GetExecutingAssembly().GetType(GetType().Namespace + ".myClass");
// calling my void Method that has no parameters.
myClassType.GetMethod("voidMethodWithoutParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);
// calling my string returning Method & passing to it two string parameters.
Object methodOutput = myClassType.GetMethod("stringReturnMethodWithParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { "value1", "value1" });
Console.WriteLine(methodOutput.ToString());
Note: I don't need to instantiate an object of myClass to use it's methods, as the methods I'm using are static
.
Great resources:
Here is how you would add query string parameters using HttpClient 4.2 and later:
URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("parts", "all").setParameter("action", "finish");
HttpPost post = new HttpPost(builder.build());
The resulting URI would look like:
http://example.com/?parts=all&action=finish
Thanks for enlightening us Cypawer.
I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi
and it worked flawlessly.
If Symfony 4 or 5, juste use this code (Where name is the name of your field):
$request->request->get('name');
This works for both GET and POST:
@Context
private HttpServletRequest httpRequest;
private void printRequest(HttpServletRequest httpRequest) {
System.out.println(" \n\n Headers");
Enumeration headerNames = httpRequest.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
}
System.out.println("\n\nParameters");
Enumeration params = httpRequest.getParameterNames();
while(params.hasMoreElements()){
String paramName = (String)params.nextElement();
System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
}
System.out.println("\n\n Row data");
System.out.println(extractPostRequestBody(httpRequest));
}
static String extractPostRequestBody(HttpServletRequest request) {
if ("POST".equalsIgnoreCase(request.getMethod())) {
Scanner s = null;
try {
s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}
return "";
}
Use the Validator to get the errors for a specific entity
if( $form->isValid() )
{
// ...
}
else
{
// get a ConstraintViolationList
$errors = $this->get('validator')->validate( $user );
$result = '';
// iterate on it
foreach( $errors as $error )
{
// Do stuff with:
// $error->getPropertyPath() : the field that caused the error
// $error->getMessage() : the error message
}
}
API reference:
I access the ticketNumber parameter for my multipart post request in the following way.
$data = $request->request->all();
$ticketNumber = $data["ticketNumber"];
Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.
/**
* HTTP request types
*/
public static final int POST_TYPE = 1;
public static final int GET_TYPE = 2;
public static final int PUT_TYPE = 3;
public static final int DELETE_TYPE = 4;
/**
* HTTP request header constants
*/
public static final String CONTENT_TYPE = "Content-Type";
public static final String ACCEPT_ENCODING = "Accept-Encoding";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String ENCODING_GZIP = "gzip";
public static final String MIME_FORM_ENCODED = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN = "text/plain";
private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
final Map<String, String> headers, final Map<String, String> params, final int requestType)
throws IOException {
DefaultHttpClient client = HTTPClientFactory.newClient();
client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);
// add user and pass to client credentials if present
if ((user != null) && (pass != null)) {
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
}
// process headers using request interceptor
final Map<String, String> sendHeaders = new HashMap<String, String>();
if ((headers != null) && (headers.size() > 0)) {
sendHeaders.putAll(headers);
}
if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
}
// request gzip encoding for response
sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);
if (sendHeaders.size() > 0) {
client.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException,
IOException {
for (String key : sendHeaders.keySet()) {
if (!request.containsHeader(key)) {
request.addHeader(key, sendHeaders.get(key));
}
}
}
});
}
//.... code omitted ....//
}
Try changing
public class LinqHelper
to
public static class LinqHelper
If it's an object method, you need to pass the object to CallObjectMethod
:
jobject result = env->CallObjectMethod(obj, messageMe, jstr);
What you were doing was the equivalent of jstr.messageMe()
.
Since your is a void method, you should call:
env->CallVoidMethod(obj, messageMe, jstr);
If you want to return a result, you need to change your JNI signature (the ()V
means a method of void
return type) and also the return type in your Java code.
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
I m invoking the weighted average through reflection. And had used method with more than one parameter.
Class cls = Class.forName(propFile.getProperty(formulaTyp));// reading class name from file
Object weightedobj = cls.newInstance(); // invoke empty constructor
Class<?>[] paramTypes = { String.class, BigDecimal[].class, BigDecimal[].class }; // 3 parameter having first is method name and other two are values and their weight
Method printDogMethod = weightedobj.getClass().getMethod("applyFormula", paramTypes); // created the object
return BigDecimal.valueOf((Double) printDogMethod.invoke(weightedobj, formulaTyp, decimalnumber, weight)); calling the method
#include<iostream>
using namespace std;
int add(int &number);
int main ()
{
int number;
int result;
number=5;
cout << "The value of the variable number before calling the function : " << number << endl;
result=add(&number);
cout << "The value of the variable number after the function is returned : " << number << endl;
cout << "The value of result : " << result << endl;
return(0);
}
int add(int &p)
{
*p=*p+100;
return(*p);
}
This is invalid code on several counts. Running it through g++ gives:
crap.cpp: In function ‘int main()’:
crap.cpp:11: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int*’
crap.cpp:3: error: in passing argument 1 of ‘int add(int&)’
crap.cpp: In function ‘int add(int&)’:
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:20: error: invalid type argument of ‘unary *’
A valid version of the code reads:
#include<iostream>
using namespace std;
int add(int &number);
int main ()
{
int number;
int result;
number=5;
cout << "The value of the variable number before calling the function : " << number << endl;
result=add(number);
cout << "The value of the variable number after the function is returned : " << number << endl;
cout << "The value of result : " << result << endl;
return(0);
}
int add(int &p)
{
p=p+100;
return p;
}
What is happening here is that you are passing a variable "as is" to your function. This is roughly equivalent to:
int add(int *p)
{
*p=*p+100;
return *p;
}
However, passing a reference to a function ensures that you cannot do things like pointer arithmetic with the reference. For example:
int add(int &p)
{
*p=*p+100;
return p;
}
is invalid.
If you must use a pointer to a reference, that has to be done explicitly:
int add(int &p)
{
int* i = &p;
i=i+100L;
return *i;
}
Which on a test run gives (as expected) junk output:
The value of the variable number before calling the function : 5
The value of the variable number after the function is returned : 5
The value of result : 1399090792
For HttpClient, we can do this :
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
String uri = new StringBuilder("url").toString();
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
HttpClient client = HttpClientBuilder.create().setSSLContext(ctx)
.setSSLHostnameVerifier(hostnameVerifier).build()
One more variant is using very powerfull JOOR library https://github.com/jOOQ/jOOR
MyObject myObject = new MyObject()
on(myObject).get("privateField");
It allows to modify any fields like final static constants and call yne protected methods without specifying concrete class in the inheritance hierarhy
<!-- https://mvnrepository.com/artifact/org.jooq/joor-java-8 -->
<dependency>
<groupId>org.jooq</groupId>
<artifactId>joor-java-8</artifactId>
<version>0.9.7</version>
</dependency>
And if you really want to get yourself in trouble, make it easier to execute by writing an extension method:
static class AccessExtensions
{
public static object call(this object o, string methodName, params object[] args)
{
var mi = o.GetType ().GetMethod (methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
if (mi != null) {
return mi.Invoke (o, args);
}
return null;
}
}
And usage:
class Counter
{
public int count { get; private set; }
void incr(int value) { count += value; }
}
[Test]
public void making_questionable_life_choices()
{
Counter c = new Counter ();
c.call ("incr", 2); // "incr" is private !
c.call ("incr", 3);
Assert.AreEqual (5, c.count);
}
A cleaner way is to set connectionString in xml file, for example Web.Confing(WepApplication)
or App.Config(StandAloneApplication)
.
<connectionStrings>
<remove name="myConn"/>
<add name="myConn" connectionString="User ID=sa;Password=XXXXX;Initial Catalog=qualitaBorri;Data Source=PC_NAME\SQLEXPRESS;Connection Timeout=60"/>
</connectionStrings>
By code you can get connection in this way:
public static SqlConnection getConnection()
{
string conn = string.Empty;
conn = System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
SqlConnection aConnection = new SqlConnection(conn);
return aConnection;
}
You can set ConnectionTimeout
only you create a instance.
When instance is create you don't change this value.
You should set both autoplay and autoplayTimeout properties. I used this code, and it works for me:
$('.owl-carousel').owlCarousel({
autoplay: true,
autoplayTimeout: 5000,
navigation: false,
margin: 10,
responsive: {
0: {
items: 1
},
600: {
items: 2
},
1000: {
items: 2
}
}
})
Here is a full example of a yes/no DialogFragment:
The class:
public class SomeDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setMessage("Sure you wanna do this!")
.setNegativeButton(android.R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do nothing (will close dialog)
}
})
.setPositiveButton(android.R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do something
}
})
.create();
}
}
To start dialog:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Create and show the dialog.
SomeDialog newFragment = new SomeDialog ();
newFragment.show(ft, "dialog");
You could also let the class implement onClickListener and use that instead of embedded listeners.
Callback to Activity
If you want to implement callback this is how it is done In your activity:
YourActivity extends Activity implements OnFragmentClickListener
and
@Override
public void onFragmentClick(int action, Object object) {
switch(action) {
case SOME_ACTION:
//Do your action here
break;
}
}
The callback class:
public interface OnFragmentClickListener {
public void onFragmentClick(int action, Object object);
}
Then to perform a callback from a fragment you need to make sure the listener is attached like this:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement listeners!");
}
}
And a callback is performed like this:
mListener.onFragmentClick(SOME_ACTION, null); // null or some important object as second parameter.
In a Unicode-aware language, the Unicode Punctuation character property is \p{P}
— which you can usually abbreviate \pP
and sometimes expand to \p{Punctuation}
for readability.
Are you using a Perl Compatible Regular Expression library?
You can use this javascript code to redirect after a specific time. Hope it will work.
setRedirectTime(function ()
{
window.location.href= 'https://www.google.com'; // the redirect URL will be here
},10000); // 10 seconds
An example from official spring manual:
<bean id="inheritedTestBean" abstract="true"
class="org.springframework.beans.TestBean">
<property name="name" value="parent"/>
<property name="age" value="1"/>
</bean>
<bean id="inheritsWithDifferentClass"
class="org.springframework.beans.DerivedTestBean"
parent="inheritedTestBean" init-method="initialize">
<property name="name" value="override"/>
<!-- the age property value of 1 will be inherited from parent -->
</bean>
Is that what you was looking for? Updated link
The KILL SESSION
command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.
Check the status to confirm:
SELECT sid, serial#, status, username FROM v$session;
You could also use IMMEDIATE clause:
ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;
The IMMEDIATE
clause does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill. Have a look at Killing Oracle Sessions.
Update If you want to kill all the sessions, you could just prepare a small script.
SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' FROM v$session;
Spool the above to a .sql
file and execute it, or, copy paste the output and run it.
To install this product you can see this tutorial: OpenCV on Ubuntu
There are listed the packages you need. So, with:
# dpkg -l | grep libcv2
# dpkg -l | grep libhighgui2
and more listed in the url you can find which packages are installed.
With
# dpkg -L libcv2
you can check where are installed
This operative is used for all debian packages.
Yes, in MS SQL Server, you can create scheduled jobs. In SQL Management Studio, navigate to the server, then expand the SQL Server Agent item, and finally the Jobs folder to view, edit, add scheduled jobs.
Try this:
<select id="sel">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" value="Change option to 2" onclick="changeOpt()"/>
<script>
function changeOpt(){
document.getElementById("sel").options[1].selected = true;
alert("changed")
}
</script>
As @oportocala mentions, an empty string will not result in the expected empty array.
So to counter, do:
str
.split(',')
.map(entry => entry.trim())
.filter(entry => entry)
For an array of expected integers, do:
str
.split(',')
.map(entry => parseInt(entry))
.filter(entry => typeof entry ==='number')
Go to
Tools > Android > Android Device Monitor
in v0.8.6. That will pull up the DDMS eclipse perspective.
Open Applicaction -> Accessories -> Terminal
Type commandline as below...
sudo apt-get install openjdk-7-jdk
Type commandline as below...
apt-cache search jdk
(Note: openjdk-7-jdk is symbolically used here. You can choose the JDK version as per your requirement.)
For "JAVA_HOME" (Environment Variable) type command as shown below, in "Terminal" using your installation path...
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk
(Note: "/usr/lib/jvm/java-7-openjdk" is symbolically used here just for demostration. You should use your path as per your installation.)
For "PATH" (Environment Variable) type command as shown below, in "Terminal" using your installation path...
export PATH=$PATH:/usr/lib/jvm/java-7-openjdk/bin
(Note: "/usr/lib/jvm/java-7-openjdk" is symbolically used here just for demostration. You should use your path as per your installation.)
Check for "open jdk" installation, just type command in "Terminal" as shown below
javac -version
Argh. Forget that. It looks like I have to get the cobwebs out of my C and C++ programming and use that instead. I do not know all the shell tricks to get it to work.
This is how far I got.
ffmpeg -i myfile 2>&1 | grep "" > textdump.txt
and then I would probably extract the duration with a C++ app instead by extracting tokens.
I am not posting the solution because I am not a nice person right now
Update - I have my approach to getting that duration time stamp
Step 1 - Get the media information on to a text file
`ffprobe -i myfile 2>&1 | grep "" > textdump.txt`
OR
`ffprobe -i myfile 2>&1 | awk '{ print }' > textdump.txt`
Step 2 - Home in on the information needed and extract it
cat textdump.txt | grep "Duration" | awk '{ print $2 }' | ./a.out
Notice the a.out. That is my C code to chop off the resulting comma because the output is something like 00:00:01.33,
Here is the C code that takes stdin and outputs the correct information needed. I had to take the greater and less than signs out for viewing.
#include stdio.h
#include string.h
void main()
{
//by Admiral Smith Nov 3. 2016
char time[80];
int len;
char *correct;
scanf("%s", &time);
correct = (char *)malloc(strlen(time));
if (!correct)
{
printf("\nmemory error");
return;
}
memcpy(correct,&time,strlen(time)-1);
correct[strlen(time)]='/0';
printf("%s", correct);
free(correct);
}
Now the output formats correctly like 00:00:01.33
SELECT name,
type
FROM dbo.sysobjects
WHERE (type = 'P')
You did not register your nib as below:
tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
Use the attr
method of jQuery like this:
alert($('input').attr('name'));
Note that you can also use attr
to set the attribute values by specifying second argument:
$('input').attr('name', 'new_name')
Let us use the following image as an example for the data in our MySQL Database:
Now, as the question mentions, we need to find the sum of a particular column in a table. For example, let us add all the values of column "duration_sec" for the date '09-10-2018' and only status 'off'
For this condition, the following would be the sql query and code:
$sql_qry = "SELECT SUM(duration_sec) AS count
FROM tbl_npt
WHERE date='09-10-2018' AND status='off'";
$duration = $connection->query($sql_qry);
$record = $duration->fetch_array();
$total = $record['count'];
echo $total;
In Calculating Work Days you can find a good article about this subject, but as you can see it is not that advanced.
--Changing current database to the Master database allows function to be shared by everyone.
USE MASTER
GO
--If the function already exists, drop it.
IF EXISTS
(
SELECT *
FROM dbo.SYSOBJECTS
WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')
AND XType IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_WorkDays]
GO
CREATE FUNCTION dbo.fn_WorkDays
--Presets
--Define the input parameters (OK if reversed by mistake).
(
@StartDate DATETIME,
@EndDate DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed
)
--Define the output data type.
RETURNS INT
AS
--Calculate the RETURN of the function.
BEGIN
--Declare local variables
--Temporarily holds @EndDate during date reversal.
DECLARE @Swap DATETIME
--If the Start Date is null, return a NULL and exit.
IF @StartDate IS NULL
RETURN NULL
--If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).
IF @EndDate IS NULL
SELECT @EndDate = @StartDate
--Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.
--Usually faster than CONVERT.
--0 is a date (01/01/1900 00:00:00.000)
SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),
@EndDate = DATEADD(dd,DATEDIFF(dd,0,@EndDate) , 0)
--If the inputs are in the wrong order, reverse them.
IF @StartDate > @EndDate
SELECT @Swap = @EndDate,
@EndDate = @StartDate,
@StartDate = @Swap
--Calculate and return the number of workdays using the input parameters.
--This is the meat of the function.
--This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.
RETURN (
SELECT
--Start with total number of days including weekends
(DATEDIFF(dd,@StartDate, @EndDate)+1)
--Subtact 2 days for each full weekend
-(DATEDIFF(wk,@StartDate, @EndDate)*2)
--If StartDate is a Sunday, Subtract 1
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'
THEN 1
ELSE 0
END)
--If EndDate is a Saturday, Subtract 1
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'
THEN 1
ELSE 0
END)
)
END
GO
If you need to use a custom calendar, you might need to add some checks and some parameters. Hopefully it will provide a good starting point.
This is probably the simplest way:
data$rownumber = 1:dim(data)[1]
It's probably worth noting that if you want to select a row by its row index, you can do this with simple bracket notation
data[3,]
vs.
data[data$rownumber==3,]
So I'm not really sure what this new column accomplishes.
To Run a .dll file..First find out what are functions it is exporting..Dll files will excecute the functions specified in the Export Category..To know what function it is Exporting refer "filealyzer" Application..It will show you the export function under "PE EXPORT" Category..Notedown the function name-- Then open the command prompt,Type Rundll32 dllname,functionname (dllname--name of your dll) (Functionname-- name of the function you found under the PE Export) Note:Makesure that your command prompt location is your dll file location
Suggest using NUnit's clean delegate syntax.
Example for testing ArgumentNullExeption
:
[Test]
[TestCase(null)]
public void FooCalculation_InvalidInput_ShouldThrowArgumentNullExeption(string text)
{
var foo = new Foo();
Assert.That(() => foo.Calculate(text), Throws.ArgumentNullExeption);
//Or:
Assert.That(() => foo.Calculate(text), Throws.Exception.TypeOf<ArgumentNullExeption>);
}
For this you need to run the "tomcat6w" application that is part of the standard Tomcat distribution in the "bin" directory. E.g. for windows the default is "C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin\tomcat6w.exe". The "tomcat6w" application starts a GUI. If you select the "Java" tab you can enter all Java options.
It is also possible to pass JVM options via the command line to tomcat. For this you need to use the command:
<tomcatexecutable> //US//<tomcatservicename> ++JvmOptions="<JVMoptions>"
where "tomcatexecutable" refers to your tomcat application, "tomcatservicename" is the tomcat service name you are using and "JVMoptions" are your JVM options. For instance:
"tomcat6.exe" //US//tomcat6 ++JvmOptions="-XX:MaxPermSize=128m"
If you want something a little bit more readable, you can try this:
<button @click="[click1($event), click2($event)]">
Multiple
</button>
To me, this solution feels more Vue-like hope you enjoy
I also face the similar Issue. Nothing programmer has to do to resolve this error. I informed to my oracle DBA team. They kill the session and worked like a charm.
I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :
function buildOptions (object) {
var validTypes = ['string', 'number', 'boolean'];
var value;
var key;
for (key in object) {
value = object[key];
if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
object[key + '=' + value] = true;
}
}
return object;
}
With this hack, an object like this:
var contact = {
"id": 1364,
"author_name": "Mr Nobody",
"notified_type": "friendship",
"action": "create"
};
Will look like this before transformation:
var contact = {
"id": 1364,
"id=1364": true,
"author_name": "Mr Nobody",
"author_name=Mr Nobody": true,
"notified_type": "friendship",
"notified_type=friendship": true,
"action": "create",
"action=create": true
};
And your mustache template will look like this:
{{#notified_type=friendship}}
friendship…
{{/notified_type=friendship}}
{{#notified_type=invite}}
invite…
{{/notified_type=invite}}
Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".
Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.
For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.
Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.
Here is an example that works:
MatchPassword(AC: FormControl) {
let dataForm = AC.parent;
if(!dataForm) return null;
var newPasswordRepeat = dataForm.get('newPasswordRepeat');
let password = dataForm.get('newPassword').value;
let confirmPassword = newPasswordRepeat.value;
if(password != confirmPassword) {
/* for newPasswordRepeat from current field "newPassword" */
dataForm.controls["newPasswordRepeat"].setErrors( {MatchPassword: true} );
if( newPasswordRepeat == AC ) {
/* for current field "newPasswordRepeat" */
return {newPasswordRepeat: {MatchPassword: true} };
}
} else {
dataForm.controls["newPasswordRepeat"].setErrors( null );
}
return null;
}
createForm() {
this.dataForm = this.fb.group({
password: [ "", Validators.required ],
newPassword: [ "", [ Validators.required, Validators.minLength(6), this.MatchPassword] ],
newPasswordRepeat: [ "", [Validators.required, this.MatchPassword] ]
});
}
Actually, you can save you picture at any place. If you want to save in a public space, so any other application can access, use this code:
storageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
),
getAlbumName()
);
The picture doesn't go to the album. To do this, you need to call a scan:
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
You can found more info at https://developer.android.com/training/camera/photobasics.html#TaskGallery
Now it has full support in latest version of major browsers like Chrome, Edge, Firefox , Safari etc. Here's the comparison between the null operator and Nullish Coalescing Operator
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
/* OR Operator */
const undefinedValue = response.settings.undefinedValue || 'Default Value'; // 'Default Value'
const nullValue = response.settings.nullValue || 'Default Value'; // 'Default Value'
const headerText = response.settings.headerText || 'Hello, world!'; // 'Hello, world!'
const animationDuration = response.settings.animationDuration || 300; // 300
const showSplashScreen = response.settings.showSplashScreen || true; // true
/* Nullish Coalescing Operator */
const undefinedValue = response.settings.undefinedValue ?? 'Default Value'; // 'Default Value'
const nullValue = response.settings.nullValue ?? ''Default Value'; // 'Default Value'
const headerText = response.settings.headerText ?? 'Hello, world!'; // ''
const animationDuration = response.settings.animationDuration ?? 300; // 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // false
Usage depends on whether the component's parent has a layout manager or not.
setSize()
-- use when a parent layout manager does not exist;setPreferredSize()
(also its related setMinimumSize
and setMaximumSize
) -- use when a parent layout manager exists.The setSize()
method probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrame
s and JWindow
s) and things that are inside of scrolled panes. You also must call setSize()
if you've got components inside a parent without a layout manager.
Generally, setPreferredSize()
will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize()
and setLocation()
to position those components according to the layout's rules.
For example, a BorderLayout
tries to make the bounds of its "north" region equal to the preferred size of its north component---they may end up larger or smaller than that, depending on the size of the JFrame
, the size of the other components in the layout, and so on.
NPM is used to manage packages and download them. However, NPX must be used as the tool to execute Node Packages
Try using NPX nodemon ...
Hope this helps!
This can done several ways. I usually do it from my class.
From class
.image
{
width:100%;
}
and for this your html would be:
<img class="image" src="images/image_name">
or if you want to style it using inline styling then you would just have:
<img style="width:100%; height:60px" id="image" src="images/image_name">
I however recommend doing it from your external style-sheet because as your project grows you will realize that the entire thing is easier managed with separate files for your html and your css.
When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.
Different order make it works :)
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
It means the SSMS login user does not have permission on the .mdf file. This is how it has worked for me:
I had opened the SSMS (Run as administrator) and login as an administrator user, database right-click attach, click add, select the .mdf file, click Ok. Done.
Use display: block;
margin: auto;
it will center the div
gmdate()
is doing exactly what you asked for.
Look at formats here: http://php.net/manual/en/function.gmdate.php
if (value){
value = (value.length > 1) ? value[0].toUpperCase() + value.substr(1).toLowerCase() : value.toUpperCase();
}
If you are in a network with multiple docker containers, make sure they are all up and running! One of my containers was down, pretty obvious if you know where to check.
First, there is no such thing as a JSON object. JSON is a string format that can be used as a representation of a Javascript object literal.
Since JSON is a string, Javascript will treat it like a string, and not like an object (or array or whatever you are trying to use it as.)
Here is a good JSON reference to clarify this difference:
http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/
So if you need accomplish the task mentioned in your question, you must convert the JSON string to an object or deal with it as a string, and not as a JSON array. There are several libraries to accomplish this. Look at http://www.json.org/js.html for a reference.
class Clock {
String time;
void setTime (String t) {
time = t;
}
String getTime() {
return time;
}
}
class ClockTestDrive {
public static void main (String [] args) {
Clock c = new Clock;
c.setTime("12345")
String tod = c.getTime();
System.out.println(time: " + tod);
}
}
When you run the program, program starts in mains,
setTime()
is called by the object c time
is set to the value passed by getTime()
is called by object ctod
and tod
get printed out This has become very easy with Jackson 2.0 and the Joda module.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
Maven dependency:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.1.1</version>
</dependency>
Code and documentation: https://github.com/FasterXML/jackson-datatype-joda
Binaries: http://repo1.maven.org/maven2/com/fasterxml/jackson/datatype/jackson-datatype-joda/
Besides Carl's answer, the "standard" C++ way is not to use a C int
array, but rather something like a C++ STL std::vector<int> list
which you can query for list.size()
.
devnull is right;
sudo update-alternatives --config x-terminal-emulator
just do:
type version.txt
and it will be displayed as if you typed:
set /p Build=<version.txt
echo %Build%
The exception message clearly speaks that the class versions, which would include the class meta data as well, has changed over time. In other words, the class structure during serialization is not the same during de-serialization. This is what is most probably "going on".
First, add a textView in the XML file
<TextView
android:id="@+id/rate_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/what_U_want_to_display_in_first_time"
/>
then add a button in xml file with id btn_change_textView and write this two line of code in onCreate()
method of activity
Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);
then use clickListener()
on button object like this
btn.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
textView.setText("write here what u want to display after button click in string");
}
});
“application/json
” is the correct JSON content type.
def ajaxFindSystems = {
def result = Systems.list()
render(contentType:'application/json') {
results {
result.each{sys->
system(id:sys.id, name:sys.name)
}
}
resultset (rows:result.size())
}
}
You can override the IIS default document setting using the web.config
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="DefaultPageToBeSet.aspx" />
</files>
</defaultDocument>
</system.webServer>
Or using the IIS, refer the link for reference http://www.iis.net/configreference/system.webserver/defaultdocument
"config": {
"platform": {
"ext-pcntl": "7.2",
"ext-posix": "7.2"
}
}
help=>install new software=>workwith choice Juno - http://download.eclipse.org/releases/juno and search in the below "type filter text" --------------market
you will see this plugs Marketplace Client
If you are styling calc in a GWT project, its parser might not parse calc for you as it did not for me... the solution is to wrap it in a css literal like this:
height: literal("-moz-calc(100% - (20px + 30px))");
height: literal("-webkit-calc(100% - (20px + 30px))");
height: literal("calc(100% - (20px + 30px))");
None
, Python's null?There's no null
in Python; instead there's None
. As stated already, the most accurate way to test that something has been given None
as a value is to use the is
identity operator, which tests that two variables refer to the same object.
>>> foo is None
True
>>> foo = 'bar'
>>> foo is None
False
None
None
is the sole instance of the class NoneType
and any further attempts at instantiating that class will return the same object, which makes None
a singleton. Newcomers to Python often see error messages that mention NoneType
and wonder what it is. It's my personal opinion that these messages could simply just mention None
by name because, as we'll see shortly, None
leaves little room to ambiguity. So if you see some TypeError
message that mentions that NoneType
can't do this or can't do that, just know that it's simply the one None
that was being used in a way that it can't.
Also, None
is a built-in constant. As soon as you start Python, it's available to use from everywhere, whether in module, class, or function. NoneType
by contrast is not, you'd need to get a reference to it first by querying None
for its class.
>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType
You can check None
's uniqueness with Python's identity function id()
. It returns the unique number assigned to an object, each object has one. If the id of two variables is the same, then they point in fact to the same object.
>>> NoneType = type(None)
>>> id(None)
10748000
>>> my_none = NoneType()
>>> id(my_none)
10748000
>>> another_none = NoneType()
>>> id(another_none)
10748000
>>> def function_that_does_nothing(): pass
>>> return_value = function_that_does_nothing()
>>> id(return_value)
10748000
None
cannot be overwrittenIn much older versions of Python (before 2.4) it was possible to reassign None
, but not any more. Not even as a class attribute or in the confines of a function.
# In Python 2.7
>>> class SomeClass(object):
... def my_fnc(self):
... self.None = 'foo'
SyntaxError: cannot assign to None
>>> def my_fnc():
None = 'foo'
SyntaxError: cannot assign to None
# In Python 3.5
>>> class SomeClass:
... def my_fnc(self):
... self.None = 'foo'
SyntaxError: invalid syntax
>>> def my_fnc():
None = 'foo'
SyntaxError: cannot assign to keyword
It's therefore safe to assume that all None
references are the same. There isn't any "custom" None
.
None
use the is
operatorWhen writing code you might be tempted to test for Noneness like this:
if value==None:
pass
Or to test for falsehood like this
if not value:
pass
You need to understand the implications and why it's often a good idea to be explicit.
None
Why do
value is None
rather than
value==None
?
The first is equivalent to:
id(value)==id(None)
Whereas the expression value==None
is in fact applied like this
value.__eq__(None)
If the value really is None
then you'll get what you expected.
>>> nothing = function_that_does_nothing()
>>> nothing.__eq__(None)
True
In most common cases the outcome will be the same, but the __eq__()
method opens a door that voids any guarantee of accuracy, since it can be overridden in a class to provide special behavior.
Consider this class.
>>> class Empty(object):
... def __eq__(self, other):
... return not other
So you try it on None
and it works
>>> empty = Empty()
>>> empty==None
True
But then it also works on the empty string
>>> empty==''
True
And yet
>>> ''==None
False
>>> empty is None
False
None
as a booleanThe following two tests
if value:
# Do something
if not value:
# Do something
are in fact evaluated as
if bool(value):
# Do something
if not bool(value):
# Do something
None
is a "falsey", meaning that if cast to a boolean it will return False
and if applied the not
operator it will return True
. Note however that it's not a property unique to None
. In addition to False
itself, the property is shared by empty lists, tuples, sets, dicts, strings, as well as 0, and all objects from classes that implement the __bool__()
magic method to return False
.
>>> bool(None)
False
>>> not None
True
>>> bool([])
False
>>> not []
True
>>> class MyFalsey(object):
... def __bool__(self):
... return False
>>> f = MyFalsey()
>>> bool(f)
False
>>> not f
True
So when testing for variables in the following way, be extra aware of what you're including or excluding from the test:
def some_function(value=None):
if not value:
value = init_value()
In the above, did you mean to call init_value()
when the value is set specifically to None
, or did you mean that a value set to 0
, or the empty string, or an empty list should also trigger the initialization? Like I said, be mindful. As it's often the case, in Python explicit is better than implicit.
None
in practiceNone
used as a signal valueNone
has a special status in Python. It's a favorite baseline value because many algorithms treat it as an exceptional value. In such scenarios it can be used as a flag to signal that a condition requires some special handling (such as the setting of a default value).
You can assign None
to the keyword arguments of a function and then explicitly test for it.
def my_function(value, param=None):
if param is None:
# Do something outrageous!
You can return it as the default when trying to get to an object's attribute and then explicitly test for it before doing something special.
value = getattr(some_obj, 'some_attribute', None)
if value is None:
# do something spectacular!
By default a dictionary's get()
method returns None
when trying to access a non-existing key:
>>> some_dict = {}
>>> value = some_dict.get('foo')
>>> value is None
True
If you were to try to access it by using the subscript notation a KeyError
would be raised
>>> value = some_dict['foo']
KeyError: 'foo'
Likewise if you attempt to pop a non-existing item
>>> value = some_dict.pop('foo')
KeyError: 'foo'
which you can suppress with a default value that is usually set to None
value = some_dict.pop('foo', None)
if value is None:
# Booom!
None
used as both a flag and valid valueThe above described uses of None
apply when it is not considered a valid value, but more like a signal to do something special. There are situations however where it sometimes matters to know where None
came from because even though it's used as a signal it could also be part of the data.
When you query an object for its attribute with getattr(some_obj, 'attribute_name', None)
getting back None
doesn't tell you if the attribute you were trying to access was set to None
or if it was altogether absent from the object. The same situation when accessing a key from a dictionary, like some_dict.get('some_key')
, you don't know if some_dict['some_key']
is missing or if it's just set to None
. If you need that information, the usual way to handle this is to directly attempt accessing the attribute or key from within a try/except
construct:
try:
# Equivalent to getattr() without specifying a default
# value = getattr(some_obj, 'some_attribute')
value = some_obj.some_attribute
# Now you handle `None` the data here
if value is None:
# Do something here because the attribute was set to None
except AttributeError:
# We're now handling the exceptional situation from here.
# We could assign None as a default value if required.
value = None
# In addition, since we now know that some_obj doesn't have the
# attribute 'some_attribute' we could do something about that.
log_something(some_obj)
Similarly with dict:
try:
value = some_dict['some_key']
if value is None:
# Do something here because 'some_key' is set to None
except KeyError:
# Set a default
value = None
# And do something because 'some_key' was missing
# from the dict.
log_something(some_dict)
The above two examples show how to handle object and dictionary cases. What about functions? The same thing, but we use the double asterisks keyword argument to that end:
def my_function(**kwargs):
try:
value = kwargs['some_key']
if value is None:
# Do something because 'some_key' is explicitly
# set to None
except KeyError:
# We assign the default
value = None
# And since it's not coming from the caller.
log_something('did not receive "some_key"')
None
used only as a valid valueIf you find that your code is littered with the above try/except
pattern simply to differentiate between None
flags and None
data, then just use another test value. There's a pattern where a value that falls outside the set of valid values is inserted as part of the data in a data structure and is used to control and test special conditions (e.g. boundaries, state, etc.). Such a value is called a sentinel and it can be used the way None
is used as a signal. It's trivial to create a sentinel in Python.
undefined = object()
The undefined
object above is unique and doesn't do much of anything that might be of interest to a program, it's thus an excellent replacement for None
as a flag. Some caveats apply, more about that after the code.
With function
def my_function(value, param1=undefined, param2=undefined):
if param1 is undefined:
# We know nothing was passed to it, not even None
log_something('param1 was missing')
param1 = None
if param2 is undefined:
# We got nothing here either
log_something('param2 was missing')
param2 = None
With dict
value = some_dict.get('some_key', undefined)
if value is None:
log_something("'some_key' was set to None")
if value is undefined:
# We know that the dict didn't have 'some_key'
log_something("'some_key' was not set at all")
value = None
With an object
value = getattr(obj, 'some_attribute', undefined)
if value is None:
log_something("'obj.some_attribute' was set to None")
if value is undefined:
# We know that there's no obj.some_attribute
log_something("no 'some_attribute' set on obj")
value = None
As I mentioned earlier, custom sentinels come with some caveats. First, they're not keywords like None
, so Python doesn't protect them. You can overwrite your undefined
above at any time, anywhere in the module it's defined, so be careful how you expose and use them. Next, the instance returned by object()
is not a singleton. If you make that call 10 times you get 10 different objects. Finally, usage of a sentinel is highly idiosyncratic. A sentinel is specific to the library it's used in and as such its scope should generally be limited to the library's internals. It shouldn't "leak" out. External code should only become aware of it, if their purpose is to extend or supplement the library's API.
eval
is not an acceptable practice if your directory names can be generated by untrusted sources. See BashFAQ #48 for more on why eval
should not be used, and BashFAQ #50 for more on the root cause of this problem and its proper solutions, some of which are touched on below:
If you need to build up your commands over time, use arrays:
tar_cmd=( tar cv "$directory" )
split_cmd=( split -b 1024m - "$backup_file" )
encrypt_cmd=( openssl des3 -salt )
"${tar_cmd[@]}" | "${encrypt_cmd[@]}" | "${split_cmd[@]}"
Alternately, if this is just about defining your commands in one central place, use functions:
tar_cmd() { tar cv "$directory"; }
split_cmd() { split -b 1024m - "$backup_file"; }
encrypt_cmd() { openssl des3 -salt; }
tar_cmd | split_cmd | encrypt_cmd
Keystore is used to store private key and identity certificates that a specific program should present to both parties (server or client) for verification.
Truststore is used to store certificates from Certified Authorities (CA) that verify the certificate presented by the server in SSL connection.
This article for reference https://www.educative.io/edpresso/keystore-vs-truststore
Spring MVC offers a standaloneSetup that supports testing relatively simple controllers, without the need of context.
Build a MockMvc by registering one or more @Controller's instances and configuring Spring MVC infrastructure programmatically. This allows full control over the instantiation and initialization of controllers, and their dependencies, similar to plain unit tests while also making it possible to test one controller at a time.
An example test for your controller can be something as simple as
public class DemoApplicationTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new HelloWorld()).build();
}
@Test
public void testSayHelloWorld() throws Exception {
this.mockMvc.perform(get("/")
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"));
}
}
Wrote a small article about inserting and deleting elements at arbitrary positions in Javascript Arrays.
Here's the small snippet to remove an element from any position. This extends the Array class in Javascript and adds the remove(index) method.
// Remove element at the given index
Array.prototype.remove = function(index) {
this.splice(index, 1);
}
So to remove the first item in your example, call arr.remove():
var arr = [1,2,3,5,6];
arr.remove(0);
To remove the second item,
arr.remove(1);
Here's a tiny article with insert and delete methods for Array class.
Essentially this is no different than the other answers using splice, but the name splice
is non-intuitive, and if you have that call all across your application, it just makes the code harder to read.
You could do it like this:
<a class="btn btn-primary announce" data-toggle="modal" data-id="107" >Announce</a>
Then use jQuery to bind the click and send the Announce data-id as the value in the modals #cafeId:
$(document).ready(function(){
$(".announce").click(function(){ // Click to only happen on announce links
$("#cafeId").val($(this).data('id'));
$('#createFormId').modal('show');
});
});
If you want to force the whiskers to extend to the max and min values, you can tweak the coef
argument. Default value for coef
is 1.5 (i.e. default length of the whiskers is 1.5 times the IQR).
# Load package and create a dummy data frame with outliers
#(using example from Ramnath's answer above)
library(ggplot2)
df = data.frame(y = c(-100, rnorm(100), 100))
# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))
# create boxplot where whiskers extend to max and min values
p1 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)), coef = 500)
This is like many other optimizations - you sacrifice some readability for speed. As John mentioned, if you've done your profiling homework and found this to be a significantly useful enough change and you need the extra speed, then go for it. It'd probably be good to put a note up with all the other imports:
from foo import bar
from baz import qux
# Note: datetime is imported in SomeClass below
After countless hours of frustration I managed to get all working:
odbcinst.ini:
[FreeTDS]
Description = FreeTDS Driver v0.91
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
fileusage=1
dontdlclose=1
UsageCount=1
odbc.ini:
[test]
Driver = FreeTDS
Description = My Test Server
Trace = No
#TraceFile = /tmp/sql.log
ServerName = mssql
#Port = 1433
instance = SQLEXPRESS
Database = usedbname
TDS_Version = 4.2
FreeTDS.conf:
[mssql]
host = hostnameOrIP
instance = SQLEXPRESS
#Port = 1433
tds version = 4.2
First test connection (mssql is a section name from freetds.conf):
tsql -S mssql -U username -P password
You must see some settings but no errors and only a 1> prompt. Use quit to exit.
Then let's test DSN/FreeTDS (test is a section name from odbc.ini; -v means verbose):
isql -v test username password -v
You must see message Connected!
I was able to use Find & Replace with the "Find what:" input field set to:
" * "
(space asterisk space with no double-quotes)
and "Replace with:" set to:
""
(nothing)
An actual JSON request would look like this:
data: '{"command":"on"}',
Where you're sending an actual JSON string. For a more general solution, use JSON.stringify()
to serialize an object to JSON, like this:
data: JSON.stringify({ "command": "on" }),
To support older browsers that don't have the JSON
object, use json2.js which will add it in.
What's currently happening is since you have processData: false
, it's basically sending this: ({"command":"on"}).toString()
which is [object Object]
...what you see in your request.
set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
The single quotes do not indicate a string, they make it starts: 'C:\
instead of C:\
so
%name%
is the usual syntax for expanding a variable, the !name!
syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION
first, or by running the command prompt with CMD /V:ON
.
Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4
to keep the current PATH content, and add something to the end.
An updated answer since that adds to what @lance-pollard already posted as working answer.
How to Install specific version of a Formula (formula used in this example is terraform
):
git log master -- Formula/terraform.rb
if you have cloned the repo locally.brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/e4ca4d2c41d4c1412994f9f1cb14993be5b2c59a/Formula/terraform.rb
I am answering bit late to this question, but someone, in future, might find this useful. The below approach, besides lots of other approaches, works best, and I personally think would better suit a web application.
@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
... other configurations
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
builder.serializationInclusion(Include.NON_EMPTY);
builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
}
}
Using python-docx, as @Chinmoy Panda 's answer shows:
for para in doc.paragraphs:
fullText.append(para.text)
However, para.text
will lost the text in w:smarttag
(Corresponding github issue is here: https://github.com/python-openxml/python-docx/issues/328), you should use the following function instead:
def para2text(p):
rs = p._element.xpath('.//w:t')
return u" ".join([r.text for r in rs])
If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.
Read the DOM with JavaScript in iframe and send it via postMessage to the top window.
More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
On Mac: Eclipse -> Preferences -> Remote Systems -> Files -> click Show Hidden Files.
Tried all solutions here but these 2 steps solved the issue:
1) manual update of open-ssl from here:
https://slproweb.com/products/Win32OpenSSL.html
2) update OpenSSL using conda update openssl
command in the Anaconda Prompt
solved the issue!
One way,
Solution Explorer > Your Project > Properties > Settings.Settings. Click on this file and add define your settings from the IDE.
Access them by
Properties.Settings.Default.MySetting = "hello world";
You could call during init or whatever Locale.setDefault() or -Duser.language=, -Duser.country=, and -Duser.variant= at the command line. Here's something on Sun's site.
Just change "String[] args" to "String args[]".
What does shapiro.test do?
shapiro.test
tests the Null hypothesis that "the samples come from a Normal distribution" against the alternative hypothesis "the samples do not come from a Normal distribution".
How to perform shapiro.test in R?
The R help page for ?shapiro.test
gives,
x - a numeric vector of data values. Missing values are allowed,
but the number of non-missing values must be between 3 and 5000.
That is, shapiro.test
expects a numeric vector as input, that corresponds to the sample you would like to test and it is the only input required. Since you've a data.frame, you'll have to pass the desired column as input to the function as follows:
> shapiro.test(heisenberg$HWWIchg)
# Shapiro-Wilk normality test
# data: heisenberg$HWWIchg
# W = 0.9001, p-value = 0.2528
Interpreting results from shapiro.test:
First, I strongly suggest you read this excellent answer from Ian Fellows on testing for normality
.
As shown above, the shapiro.test
tests the NULL hypothesis that the samples came from a Normal distribution. This means that if your p-value <= 0.05, then you would reject the NULL hypothesis that the samples came from a Normal distribution. As Ian Fellows nicely put it, you are testing against the assumption of Normality". In other words (correct me if I am wrong), it would be much better if one tests the NULL hypothesis that the samples do not come from a Normal distribution. Why? Because, rejecting a NULL hypothesis is not the same as accepting the alternative hypothesis.
In case of the null hypothesis of shapiro.test
, a p-value <= 0.05 would reject the null hypothesis that the samples come from normal distribution. To put it loosely, there is a rare chance that the samples came from a normal distribution. The side-effect of this hypothesis testing is that this rare chance happens very rarely. To illustrate, take for example:
set.seed(450)
x <- runif(50, min=2, max=4)
shapiro.test(x)
# Shapiro-Wilk normality test
# data: runif(50, min = 2, max = 4)
# W = 0.9601, p-value = 0.08995
So, this (particular) sample runif(50, min=2, max=4)
comes from a normal distribution according to this test. What I am trying to say is that, there are many many cases under which the "extreme" requirements (p < 0.05) are not satisfied which leads to acceptance of "NULL hypothesis" most of the times, which might be misleading.
Another issue I'd like to quote here from @PaulHiemstra from under comments about the effects on large sample size:
An additional issue with the Shapiro-Wilk's test is that when you feed it more data, the chances of the null hypothesis being rejected becomes larger. So what happens is that for large amounts of data even very small deviations from normality can be detected, leading to rejection of the null hypothesis event though for practical purposes the data is more than normal enough.
Although he also points out that R's data size limit protects this a bit:
Luckily shapiro.test protects the user from the above described effect by limiting the data size to 5000.
If the NULL hypothesis were the opposite, meaning, the samples do not come from a normal distribution, and you get a p-value < 0.05, then you conclude that it is very rare that these samples do not come from a normal distribution (reject the NULL hypothesis). That loosely translates to: It is highly likely that the samples are normally distributed (although some statisticians may not like this way of interpreting). I believe this is what Ian Fellows also tried to explain in his post. Please correct me if I've gotten something wrong!
@PaulHiemstra also comments about practical situations (example regression) when one comes across this problem of testing for normality:
In practice, if an analysis assumes normality, e.g. lm, I would not do this Shapiro-Wilk's test, but do the analysis and look at diagnostic plots of the outcome of the analysis to judge whether any assumptions of the analysis where violated too much. For linear regression using lm this is done by looking at some of the diagnostic plots you get using plot(lm()). Statistics is not a series of steps that cough up a few numbers (hey p < 0.05!) but requires a lot of experience and skill in judging how to analysis your data correctly.
Here, I find the reply from Ian Fellows to Ben Bolker's comment under the same question already linked above equally (if not more) informative:
For linear regression,
Don't worry much about normality. The CLT takes over quickly and if you have all but the smallest sample sizes and an even remotely reasonable looking histogram you are fine.
Worry about unequal variances (heteroskedasticity). I worry about this to the point of (almost) using HCCM tests by default. A scale location plot will give some idea of whether this is broken, but not always. Also, there is no a priori reason to assume equal variances in most cases.
Outliers. A cooks distance of > 1 is reasonable cause for concern.
Those are my thoughts (FWIW).
Hope this clears things up a bit.
Note: I found this question looking for one of the steps in the answer to how to resize an existing array.
So I thought I would add that information here, in case anyone else was searching for how to do a ranged copy as a partial answer to the question of resizing an array.
For anyone else finding this question looking for the same thing I was, it is very simple:
Array.Resize<T>(ref arrayVariable, newSize);
where T is the type, i.e. where arrayVariable is declared:
T[] arrayVariable;
That method handles null checks, as well as newSize==oldSize having no effect, and of course silently handles the case where one of the arrays is longer than the other.
See the MSDN article for more.
The better answers to this only work for specific lengths of lists that are provided.
Here's a version that works for any lengths of input. It also makes the algorithm clear in terms of the mathematical concepts of combination and permutation.
from itertools import combinations, permutations
list1 = ['1', '2']
list2 = ['A', 'B', 'C']
num_elements = min(len(list1), len(list2))
list1_combs = list(combinations(list1, num_elements))
list2_perms = list(permutations(list2, num_elements))
result = [
tuple(zip(perm, comb))
for comb in list1_combs
for perm in list2_perms
]
for idx, ((l11, l12), (l21, l22)) in enumerate(result):
print(f'{idx}: {l11}{l12} {l21}{l22}')
This outputs:
0: A1 B2
1: A1 C2
2: B1 A2
3: B1 C2
4: C1 A2
5: C1 B2
You have included the dependency for sflj's api, but not the dependency for the implementation of the api, that is a separate jar, you could try slf4j-simple-1.6.1.jar.
So in my answer there are 3 different ways to redirect programmatically to a route. Some of the solutions has been presented already but the following ones focused only for functional components with an additional demo application.
Using the following versions:
react: 16.13.1
react-dom: 16.13.1
react-router: 5.2.0
react-router-dom: 5.2.0
typescript: 3.7.2
Configuration:
So first of all the solution is using HashRouter
, configured as follows:
<HashRouter>
// ... buttons for redirect
<Switch>
<Route exact path="/(|home)" children={Home} />
<Route exact path="/usehistory" children={UseHistoryResult} />
<Route exact path="/withrouter" children={WithRouterResult} />
<Route exact path="/redirectpush" children={RedirectPushResult} />
<Route children={Home} />
</Switch>
</HashRouter>
From the documentation about <HashRouter>
:
A
<Router>
that uses the hash portion of the URL (i.e.window.location.hash
) to keep your UI in sync with the URL.
Solutions:
<Redirect>
to push using useState
:Using in a functional component (RedirectPushAction
component from my repository) we can use useState
to handle redirect. Tricky part is once the redirection happened we need to set the redirect
state back to false
. By using setTimeOut
with 0
delay we are waiting until React commits Redirect
to the DOM then getting back the button in order to use next time.
Please find my example below:
const [redirect, setRedirect] = useState(false);
const handleRedirect = useCallback(() => {
let render = null;
if (redirect) {
render = <Redirect to="/redirectpush" push={true} />
// in order wait until commiting to the DOM
// and get back the button for clicking next time
setTimeout(() => setRedirect(false), 0);
}
return render;
}, [redirect]);
return <>
{handleRedirect()}
<button onClick={() => setRedirect(true)}>
Redirect push
</button>
</>
From <Redirect>
documentation:
Rendering a
<Redirect>
will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
useHistory
hook:In my solution there is a component called UseHistoryAction
which represents the following:
let history = useHistory();
return <button onClick={() => { history.push('/usehistory') }}>
useHistory redirect
</button>
The
useHistory
hook gives us access to the history object which helps us programmatically navigate or change routes.
withRouter
, get the history
from props
:Created one component called WithRouterAction
, displays as below:
const WithRouterAction = (props:any) => {
const { history } = props;
return <button onClick={() => { history.push('/withrouter') }}>
withRouter redirect
</button>
}
export default withRouter(WithRouterAction);
Reading from withRouter
documentation:
You can get access to the
history
object's properties and the closest<Route>
's match via thewithRouter
higher-order component.withRouter
will pass updatedmatch
,location
, andhistory
props to the wrapped component whenever it renders.
Demo:
For better representation I have built a GitHub repository with these examples, please find it below:
https://github.com/norbitrial/react-router-programmatically-redirect-examples
I hope this helps!
If anyone would like the answer in Swift :
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) // Change .Dark into .Light if you'd like.
var blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = theImage.bounds // 'theImage' is an image. I think you can apply this to the view too!
Update :
As of now, it's available under the IB so you don't have to code anything for it :)
A struct (without a typedef) often needs to (or should) be with the keyword struct when used.
struct A; // forward declaration
void function( struct A *a ); // using the 'incomplete' type only as pointer
If you typedef your struct you can leave out the struct keyword.
typedef struct A A; // forward declaration *and* typedef
void function( A *a );
Note that it is legal to reuse the struct name
Try changing the forward declaration to this in your code:
typedef struct context context;
It might be more readable to do add a suffix to indicate struct name and type name:
typedef struct context_s context_t;
Above solution was missing thing, and below code should work in every situation:
Windows Registry Editor Version 5.00
;
; Tell IE to open JSON documents in the browser.
; 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" .
;
[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00
[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/x-json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00
[HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00
Just save it file json.reg, and run to modify your registry.
printf
doesn't do that -- and printf
is overkill for printing a single character.
char c = '*';
int count = 42;
for (i = 0; i < count; i ++) {
putchar(c);
}
Don't worry about this being inefficient; putchar()
buffers its output, so it won't perform a physical output operation for each character unless it needs to.
Below are two functions: dbo.HexToInt and dbo.IntToHex, I use them for such conversion:
if OBJECT_ID('dbo.HexToInt') is not null
drop function dbo.HexToInt
GO
create function dbo.HexToInt (@chars varchar(max))
returns int
begin
declare @char varchar(1), @len int, @i int, @r int, @tmp int, @pow int
set @chars = RTRIM(LTRIM(@chars))
set @len = LEN(@chars)
set @i = 1
set @r = 0
while @i <= @len
begin
set @pow = @len - @i
set @char = SUBSTRING(@chars, @i, 1)
if @char = '0'
set @tmp = 0
else if @char = '1'
set @tmp = 1
else if @char = '2'
set @tmp = 2
else if @char = '3'
set @tmp = 3
else if @char = '4'
set @tmp = 4
else if @char = '5'
set @tmp = 5
else if @char = '6'
set @tmp = 6
else if @char = '7'
set @tmp = 7
else if @char = '8'
set @tmp = 8
else if @char = '9'
set @tmp = 9
else if @char = 'A'
set @tmp = 10
else if @char = 'B'
set @tmp = 11
else if @char = 'C'
set @tmp = 12
else if @char = 'D'
set @tmp = 13
else if @char = 'E'
set @tmp = 14
else if @char = 'F'
set @tmp = 15
set @r = @r + @tmp * POWER(16,@pow)
set @i = @i + 1
end
return @r
end
And the second one:
if OBJECT_ID('dbo.IntToHex') is not null
drop function dbo.IntToHex
GO
create function dbo.IntToHex (@val int)
returns varchar(max)
begin
declare @r varchar(max), @tmp int, @v1 int, @v2 int, @char varchar(1)
set @tmp = @val
set @r = ''
while 1=1
begin
set @v1 = @tmp / 16
set @v2 = @tmp % 16
if @v2 = 0
set @char = '0'
else if @v2 = 1
set @char = '1'
else if @v2 = 2
set @char = '2'
else if @v2 = 3
set @char = '3'
else if @v2 = 4
set @char = '4'
else if @v2 = 5
set @char = '5'
else if @v2 = 6
set @char = '6'
else if @v2 = 7
set @char = '7'
else if @v2 = 8
set @char = '8'
else if @v2 = 9
set @char = '9'
else if @v2 = 10
set @char = 'A'
else if @v2 = 11
set @char = 'B'
else if @v2 = 12
set @char = 'C'
else if @v2 = 13
set @char = 'D'
else if @v2 = 14
set @char = 'E'
else if @v2 = 15
set @char = 'F'
set @tmp = @v1
set @r = @char + @r
if @tmp = 0
break
end
return @r
end
It didn't. Your compiler did, but there's still a debug symbol for the original variable name.
Chosen answer (nor any of the other answers) didn't work for me, but this did:
img {outline:1px solid transparent;}
This sample works with native JavaScript where the checkbox variable name varies, i.e. not all "foo."
<!DOCTYPE html>
<html>
<body>
<p>Toggling checkboxes</p>
<script>
function getcheckboxes() {
var node_list = document.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i < node_list.length; i++)
{
var node = node_list[i];
if (node.getAttribute('type') == 'checkbox')
{
checkboxes.push(node);
}
}
return checkboxes;
}
function toggle(source) {
checkboxes = getcheckboxes();
for (var i = 0 n = checkboxes.length; i < n; i++)
{
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" name="foo1" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo2" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo3" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo4" value="bar4"> Bar 4<br/>
<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>
</body>
</html>
Compiling Programs on Windows 7:
You have to download configured Borland Compiler from http://www.4shared.com/get/Gs41_5yA/borland_for_graphics.html or http://dwij.co.in/graphics-c-programming-for-windows-7-borland-compiler/.
Put your Borland’s ‘bin’ folder into Environmental Variables.
Now go inside folder ‘bin’ & edit file bcc32.cfg as per your folder structure. This file contains settings of headers & libraries.
-I"D:\Borland\include;"
-L"D:\Borland\lib;D:\Borland\Lib\PSDK"
Now create any C/C++ Program say myprogram.cpp
Use following command to compile this bunch of code:
F:\>bcc32 myprogram.cpp
If you rely on client-side technology, it can be circumvented. Javascript may be disabled, for example. Or user might execute a JS script to work around your restrictions.
My guess is you can only do this by server-side tracking of the user session, and redirecting (as in Server.Transfer, not Response.Redirect) the user/browser to the required page.
To sort an object datasource that returns a dataset you use the Sort property of the control.
Example usage In the aspx page to sort by ascending order of ColumnName
<asp:ObjectDataSource ID="dsData" runat="server" TableName="Data"
Sort="ColumnName ASC" />
The null check is really done nice with guard keyword in swift. It improves the code readability and the scope of the variables are still available after the nil checks if you want to use them.
func setXYX -> Void{
guard a != nil else {
return;
}
guard b != nil else {
return;
}
print (" a and b is not null");
}
Get your object's constructor function and then inspect its name property.
myObj.constructor.name
Returns "myClass".
You don't have a field named user_email
in the members table
... as for why, I'm not sure as the code "looks" like it should try to join on different fields
Does the Auth::attempt method perform a join of the schema?
Run grep -Rl 'class Auth' /path/to/framework
and find where the attempt
method is and what it does.
From the docs
IF boolean-expression THEN
statements
ELSE
statements
END IF;
So in your above example the code should look as follows:
IF select count(*) from orders > 0
THEN
DELETE from orders
ELSE
INSERT INTO orders values (1,2,3);
END IF;
You were missing: END IF;
Complate Angular Way ( Set/Get value by Id ):
// In Html tag
<button (click) ="setValue()">Set Value</button>
<input type="text" #userNameId />
// In component .ts File
export class testUserClass {
@ViewChild('userNameId') userNameId: ElementRef;
ngAfterViewInit(){
console.log(this.userNameId.nativeElement.value );
}
setValue(){
this.userNameId.nativeElement.value = "Sample user Name";
}
}
I'm giving this example because this actually work for my use case.
I was trying to use the AWS Rekognition API. The API returns a BoundingBox object:
BoundingBox boundingBox = faceDetail.getBoundingBox();
The code below uses it to crop the image:
import com.amazonaws.services.rekognition.model.BoundingBox;
private BufferedImage cropImage(BufferedImage image, BoundingBox box) {
Rectangle goal = new Rectangle(Math.round(box.getLeft()* image.getWidth()),Math.round(box.getTop()* image.getHeight()),Math.round(box.getWidth() * image.getWidth()), Math.round(box.getHeight() * image.getHeight()));
Rectangle clip = goal.intersection(new Rectangle(image.getWidth(), image.getHeight()));
BufferedImage clippedImg = image.getSubimage(clip.x, clip.y , clip.width, clip.height);
return clippedImg;
}
When available, I believe that most lodash array functions will show the iteration. But sorting isn't really an iteration in the same way: when you're on the number 66, you aren't processing the fourth item in the array until it's finished. A custom sort function will loop through an array a number of times, nudging adjacent numbers forward or backward, until the everything is in its proper place.
As of pandas 0.17.0, DataFrame.sort()
is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values
As such, the answer to your question would now be
df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)
Marc's answer is of course the right answer. But since he mentioned the shift operators and unsafe code as an alternative. I would like to share a less common alternative. Using a struct with Explicit
layout. This is similar in principal to a C/C++ union
.
Here is an example of a struct that can be used to get to the component bytes of the Int32 data type and the nice thing is that it is two way, you can manipulate the byte values and see the effect on the Int.
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct Int32Converter
{
[FieldOffset(0)] public int Value;
[FieldOffset(0)] public byte Byte1;
[FieldOffset(1)] public byte Byte2;
[FieldOffset(2)] public byte Byte3;
[FieldOffset(3)] public byte Byte4;
public Int32Converter(int value)
{
Byte1 = Byte2 = Byte3 = Byte4 = 0;
Value = value;
}
public static implicit operator Int32(Int32Converter value)
{
return value.Value;
}
public static implicit operator Int32Converter(int value)
{
return new Int32Converter(value);
}
}
The above can now be used as follows
Int32Converter i32 = 256;
Console.WriteLine(i32.Byte1);
Console.WriteLine(i32.Byte2);
Console.WriteLine(i32.Byte3);
Console.WriteLine(i32.Byte4);
i32.Byte2 = 2;
Console.WriteLine(i32.Value);
Of course the immutability police may not be excited about the last possiblity :)
I'm using Ubuntu 18.04 LTS. Most of the time, when I change my java
version, I also want to use the same javac
version.
I use update-alternatives
this way, using a java_home
alternative instead :
Install every java version in /opt/java/<version>
, for example
~$ ll /opt/java/
total 24
drwxr-xr-x 6 root root 4096 jan. 22 21:14 ./
drwxr-xr-x 9 root root 4096 feb. 7 13:40 ../
drwxr-xr-x 8 stephanecodes stephanecodes 4096 jan. 8 2019 jdk-11.0.2/
drwxr-xr-x 7 stephanecodes stephanecodes 4096 dec. 15 2018 jdk1.8.0_201/
Configure alternatives
~$ sudo update-alternatives --install /opt/java/current java_home /opt/java/jdk-11.0.2/ 100
~$ sudo update-alternatives --install /opt/java/current java_home /opt/java/jdk1.8.0_201 200
Declare JAVA_HOME
(In this case, I use a global initialization script for this)
~$ sudo sh -c 'echo export JAVA_HOME=\"/opt/java/current\" >> environment.sh'
Log Out or restart Ubuntu (this will reload /etc/profile.d/environment.sh
)
Change java version
Choose the version you want to use
~$ sudo update-alternatives --config java_home
There are 2 choices for the alternative java_home (providing /opt/java/current).
Selection Path Priority Status
------------------------------------------------------------
0 /opt/java/jdk-11.0.2 200 auto mode
1 /opt/java/jdk-11.0.2 200 manual mode
* 2 /opt/java/jdk1.8.0_201 100 manual mode
Press <enter> to keep the current choice[*], or type selection number:
Check version
~$ java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
~$ javac -version
javac 11.0.2
Tip
Add the following line to ~/.bash_aliases
file :
alias change-java-version="sudo update-alternatives --config java_home && java -version && javac -version"
Now use the change-java-version
command to change java version
The IPv6 addresses for fields like RemoteAddr
from http.Request
are formatted as "[::1]:53343"
So net.SplitHostPort
works great:
package main
import (
"fmt"
"net"
)
func main() {
host1, port, err := net.SplitHostPort("127.0.0.1:5432")
fmt.Println(host1, port, err)
host2, port, err := net.SplitHostPort("[::1]:2345")
fmt.Println(host2, port, err)
host3, port, err := net.SplitHostPort("localhost:1234")
fmt.Println(host3, port, err)
}
Output is:
127.0.0.1 5432 <nil>
::1 2345 <nil>
localhost 1234 <nil>
After trying all the obvious things, and some of the other suggestions here, with no luck whatsoever, a Google search led to this link (link not working anymore) - Subversion says: Your file or directory is probably out-of-date
In a nutshell, the trick is to go to the .svn directory (in the directory that contains the offending file), and delete the "all-wcprops" file.
Worked for me when nothing else did.
My scenario is little different, but the intent is same i would like to know when the parent window hosting my user control is closing/closed as The view(i.e my usercontrol) should invoke the presenters oncloseView to execute some functionality and perform clean up. ( well we are implementing a MVP pattern on a WPF PRISM application).
I just figured that in the Loaded event of the usercontrol, i can hook up my ParentWindowClosing method to the Parent windows Closing event. This way my Usercontrol can be aware when the Parent window is being closed and act accordingly!
However, interface is 100% abstract class and abstract class can implements interface(100% abstract class) without implement its methods. What is the problem when it is defining as "interface" ?
This is simply a matter of convention. The writers of the java language decided that "extends" is the best way to describe this relationship, so that's what we all use.
In general, even though an interface is "a 100% abstract class," we don't think about them that way. We usually think about interfaces as a promise to implement certain key methods rather than a class to derive from. And so we tend to use different language for interfaces than for classes.
As others state, there are good reasons for choosing "extends" over "implements."
<?php
$subject = "this is a subject";
$message = "testing a message";
$headers .= "Reply-To: The Sender <[email protected]>\r\n";
$headers .= "Return-Path: The Sender <[email protected]>\r\n";
$headers .= "From: The Sender <[email protected]>\r\n";
$headers .= "Organization: Sender Organization\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
mail("[email protected]", $subject, $message, $headers);
?>
Just to add to these answers, In my case I had no local mySQL server, it was running inside a docker container. So the socket file does not exist and will not be accessible for the "mysql" client.
The sock file gets created by mysqld and mysql uses this to communicate with it. However if your mySql server is not running local, it does not require the sock file.
By specifying a host name/ip the sock file is not required e.g.
mysql --host=127.0.0.1 --port=3306 --user=xyz --password=xyz
Here's also a generic function that can format to any number of decimal places:
function numberFormat(val, decimalPlaces) {
var multiplier = Math.pow(10, decimalPlaces);
return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
}
You can do it like this:
angular.element('#modal').modal('hide');
Try both of these commands and see for yourself why arp is faster:
for ip in $(seq 1 254); do ping -c 1 10.185.0.$ip > /dev/null; [ $? -eq 0 ] && echo "10.185.0.$ip UP" || : ; done
for ip in $(seq 1 254); do arp -n 10.185.0.$ip | grep Address; [ $? -eq 0 ] && echo "10.185.0.$ip UP" || : ; done
if you are working in PHP version 7.2 then you have to install
sudo apt-get install php7.2-gd
Enabling Fractions/Cents/Decimals for Number Input
In order to allow fractions (cents) on an HTML5 number input, you need to specify the "step" attribute to = "any":
<input type="number" min="1" step="any" />
This will specifically keep Chrome from displaying an error when a decimal/fractional currency is entered into the input. Mozilla, IE, etc... don't error out if you forget to specify step="any"
. W3C spec states that step="any" should, indeed, be needed to allow for decimals. So, you should definitely use it. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step
Note that if you want the up/down buttons to do a specific granularity, then you must specify a numeric step such as ".01".
Also, the number input is now pretty widely supported (>90% of users).
What Input Options are there for Money/Currency?
The title of the question has since changed and takes on a slightly different meaning. One could use both number or text input in order to accept money/decimals.
For an input field for currency/money, it is recommended to use input type of number and specify appropriate attributes as outlined above. As of 2020, there is not a W3C spec for an actual input type of currency or money.
Main reason being it automatically coerces the users into entering a valid standard currency format and disallows any alphanumeric text. With that said, you could certainly use the regular text input and do some post processing to only grab the numeric/decimal value (there should be server side validation on this at some point as well).
The OP detailed a requirement of currency symbols and commas. If you want fancier logic/formatting like that, (as of 2020) you'll need to create custom JS logic for a text input or find a plugin.
Your element does not have an ID but just a name. So you could either use getElementsByName()
method to get a list of all elements with this name:
var jobValue = document.getElementsByName('txtJob')[0].value // first element in DOM (index 0) with name="txtJob"
Or you assign an ID to the element:
<input type="text" name="txtJob" id="txtJob" value="software engineer">
$(document).ready(function() {
scope.$apply(function() {
applyHeight();
});
});
This also ensures that all the scripts have been loaded before the execution of the statements. If you dont need that you can use
$(window).load(function() {
scope.$apply(function() {
applyHeight();
});
});
You can use all
> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE
On a similar note, if you want to check whether any of the elements is TRUE you can use any
> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE
Android SDK build tools are used to debug, build, run and test an Android application.
Android Build Tools can be used to develop and work from command line or IDE (i.e Eclipse or Android Studio).
Also used to connect Android devices and root them.(fastboot, adb and more..)
Always use the latest.(Recommended)
test = data.frame(C=c(0,2,4, 7, 8), A=c(4,2,4, 7, 8), B=c(1, 3, 8,3,2))
Using the simple following function replacement can be performed (but only if data frame does not have many columns):
test <- test[, c("A", "B", "C")]
for others:
test <- test[, c("B", "A", "C")]
@Edinator have a look on this..
myLabel.font = [UIFont boldSystemFontOfSize:16.0f]
myLabel.font = [UIFont italicSystemFontOfSize:16.0f];
use any one of the above at a time you want
The solution you want is the one proposed here:
https://stackoverflow.com/a/542802/50776
Basically, you do this:
cast(floor(cast(@dateVariable as float)) as datetime)
There is a function definition in the link which will allow you to consolidate the functionality and call it anywhere (instead of having to remember it) if you wish.
I have just come back to this and I had to install scipy as matplotlib.mlab gave me the error message MatplotlibDeprecationWarning: scipy.stats.norm.pdf
when trying example above. So the sample is now:
%matplotlib inline
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats
mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma))
plt.show()
Enter the following code in the opened settings file
{
"editor.formatOnSave": true
}
Save file
I use this sequence (not a 'linear' shortcut but useful anyway):
(they use the android studio menu)
No.
What are you trying to do?
workaround:
int main(void)
{
struct foo
{
void operator()() { int a = 1; }
};
foo b;
b(); // call the operator()
}
So to make your expression work, changing &&
for -a
will do the trick.
It is correct like this:
if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
then ....
or like
if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
then ....
or even
if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
then ....
You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.
Possibly you can refer to this link http://docs.oracle.com/javase/6/docs/api/java/util/List.html
List is an interface.ArrayList,LinkedList etc are classes which implement list.Whenyou are using List Interface,you have to itearte elements using ListIterator and can move forward and backward,in the List where as in ArrayList Iterate using Iterator and its elements can be accessed unidirectional way.
In Python like Andrea Ambu, but not hardcoded for choosing three.
def combinations(list, k):
"""Choose combinations of list, choosing k elements(no repeats)"""
if len(list) < k:
return []
else:
seq = [i for i in range(k)]
while seq:
print [list[index] for index in seq]
seq = get_next_combination(len(list), k, seq)
def get_next_combination(num_elements, k, seq):
index_to_move = find_index_to_move(num_elements, seq)
if index_to_move == None:
return None
else:
seq[index_to_move] += 1
#for every element past this sequence, move it down
for i, elem in enumerate(seq[(index_to_move+1):]):
seq[i + 1 + index_to_move] = seq[index_to_move] + i + 1
return seq
def find_index_to_move(num_elements, seq):
"""Tells which index should be moved"""
for rev_index, elem in enumerate(reversed(seq)):
if elem < (num_elements - rev_index - 1):
return len(seq) - rev_index - 1
return None
You need to create a C API for exposing the functionality of your C++ code. Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created.
Your C API can optionally follow an object-oriented style, even though C is not object-oriented. Ex:
// *.h file
// ...
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
typedef void* mylibrary_mytype_t;
EXTERNC mylibrary_mytype_t mylibrary_mytype_init();
EXTERNC void mylibrary_mytype_destroy(mylibrary_mytype_t mytype);
EXTERNC void mylibrary_mytype_doit(mylibrary_mytype_t self, int param);
#undef EXTERNC
// ...
// *.cpp file
mylibrary_mytype_t mylibrary_mytype_init() {
return new MyType;
}
void mylibrary_mytype_destroy(mylibrary_mytype_t untyped_ptr) {
MyType* typed_ptr = static_cast<MyType*>(untyped_ptr);
delete typed_ptr;
}
void mylibrary_mytype_doit(mylibrary_mytype_t untyped_self, int param) {
MyType* typed_self = static_cast<MyType*>(untyped_self);
typed_self->doIt(param);
}
<xsl:call-template>
is a close equivalent to calling a function in a traditional programming language.
You can define functions in XSLT, like this simple one that outputs a string.
<xsl:template name="dosomething">
<xsl:text>A function that does something</xsl:text>
</xsl:template>
This function can be called via <xsl:call-template name="dosomething">
.
<xsl:apply-templates>
is a little different and in it is the real power of XSLT: It takes any number of XML nodes (whatever you define in the select
attribute), iterates them (this is important: apply-templates works like a loop!) and finds matching templates for them:
<!-- sample XML snippet -->
<xml>
<foo /><bar /><baz />
</xml>
<!-- sample XSLT snippet -->
<xsl:template match="xml">
<xsl:apply-templates select="*" /> <!-- three nodes selected here -->
</xsl:template>
<xsl:template match="foo"> <!-- will be called once -->
<xsl:text>foo element encountered</xsl:text>
</xsl:template>
<xsl:template match="*"> <!-- will be called twice -->
<xsl:text>other element countered</xsl:text>
</xsl:template>
This way you give up a little control to the XSLT processor - not you decide where the program flow goes, but the processor does by finding the most appropriate match for the node it's currently processing.
If multiple templates can match a node, the one with the more specific match expression wins. If more than one matching template with the same specificity exist, the one declared last wins.
You can concentrate more on developing templates and need less time to do "plumbing". Your programs will become more powerful and modularized, less deeply nested and faster (as XSLT processors are optimized for template matching).
A concept to understand with XSLT is that of the "current node". With <xsl:apply-templates>
the current node moves on with every iteration, whereas <xsl:call-template>
does not change the current node. I.e. the .
within a called template refers to the same node as the .
in the calling template. This is not the case with apply-templates.
This is the basic difference. There are some other aspects of templates that affect their behavior: Their mode
and priority
, the fact that templates can have both a name
and a match
. It also has an impact whether the template has been imported (<xsl:import>
) or not. These are advanced uses and you can deal with them when you get there.
sounds silly but font-size:0; might just work. It did for me. And you can easily override this with the child element you need to show.
1: C is a type of computer programming language. While embedded C is a set of language extensions for the C Programming language.
2: C has a free-format program source code, in a desktop computer. while embedded C has different format based on embedded processor (micro- controllers/microprocessors).
3: C have normal optimization, in programming. while embedded C high level optimization in programming.
4: C programming must have required operating system. while embedded C may or may not be required operating system.
5: C can use resources from OS, memory, etc, i.e all resources from desktop computer can be used by C. while embedded C can use limited resources, like RAM, ROM, and I/Os on an embedded processor.
Hopefully this would get you started
See it live on http://ideone.com/l23He (using stdin)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* getfield(char* line, int num)
{
const char* tok;
for (tok = strtok(line, ";");
tok && *tok;
tok = strtok(NULL, ";\n"))
{
if (!--num)
return tok;
}
return NULL;
}
int main()
{
FILE* stream = fopen("input", "r");
char line[1024];
while (fgets(line, 1024, stream))
{
char* tmp = strdup(line);
printf("Field 3 would be %s\n", getfield(tmp, 3));
// NOTE strtok clobbers tmp
free(tmp);
}
}
Output:
Field 3 would be nazwisko
Field 3 would be Kowalski
Field 3 would be Nowak
First you create a MySQL table to store images, like for example:
create table testblob (
image_id tinyint(3) not null default '0',
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_ctgy varchar(25) not null default '',
image_name varchar(50) not null default ''
);
Then you can write an image to the database like:
/***
* All of the below MySQL_ commands can be easily
* translated to MySQLi_ with the additions as commented
***/
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli
// $link = mysqli_connect("localhost", $username, $password,$dbname);
$sql = sprintf("INSERT INTO testblob
(image_type, image, image_size, image_name)
VALUES
('%s', '%s', '%d', '%s')",
/***
* For all mysqli_ functions below, the syntax is:
* mysqli_whartever($link, $functionContents);
***/
mysql_real_escape_string($size['mime']),
mysql_real_escape_string($imgData),
$size[3],
mysql_real_escape_string($_FILES['userfile']['name'])
);
mysql_query($sql);
You can display an image from the database in a web page with:
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);
Prime numbers are numbers that are bigger than one and cannot be divided evenly by any other number except 1 and itself.
@This program will show you the given number is prime or not, and will show you for non prime number that it's divisible by (a number) which is rather than 1 or itself?@
Console.Write("Please Enter a number: ");
int number = int.Parse(Console.ReadLine());
int count = 2;
// this is initial count number which is greater than 1
bool prime = true;
// used Boolean value to apply condition correctly
int sqrtOfNumber = (int)Math.Sqrt(number);
// square root of input number this would help to simplify the looping.
while (prime && count <= sqrtOfNumber)
{
if ( number % count == 0)
{
Console.WriteLine($"{number} isn't prime and it divisible by
number {count}"); // this will generate a number isn't prime and it is divisible by a number which is rather than 1 or itself and this line will proves why it's not a prime number.
prime = false;
}
count++;
}
if (prime && number > 1)
{
Console.WriteLine($"{number} is a prime number");
}
else if (prime == true)
// if input is 1 or less than 1 then this code will generate
{
Console.WriteLine($"{number} isn't a prime");
}
I agree with Chris Pratt. But I think it's better to create the symlink to original Django folder where the admin templates place in:
ln -s /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/ templates/django_admin
and as you can see it depends on python version and the folder where the Django installed. So in future or on a production server you might need to change the path.
In header.php
insert this code to show menu:
<?php
wp_nav_menu(
array(
'theme_location' => 'menu-one',
'walker' => new Custom_Walker_Nav_Menu_Top
)
);
?>
In functions.php
use this:
class Custom_Walker_Nav_Menu_top extends Walker_Nav_Menu
{
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$is_current_item = '';
if(array_search('current-menu-item', $item->classes) != 0)
{
$is_current_item = ' class="active"';
}
echo '<li'.$is_current_item.'><a href="'.$item->url.'">'.$item->title;
}
function end_el( &$output, $item, $depth = 0, $args = array() ) {
echo '</a></li>';
}
}
I realize this may be a bit late, but I stumbled upon this and was wondering how to handle situations with multiple identical values, but different keys (as per bigbearzhu's comment).
So I modified Stephan Muller's answer slightly:
A datalist with non-unique values:
<input list="answers" name="answer" id="answerInput">
<datalist id="answers">
<option value="42">The answer</option>
<option value="43">The answer</option>
<option value="44">Another Answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
When the user selects an option, the browser replaces input.value
with the value
of the datalist
option instead of the innerText
.
The following code then checks for an option
with that value
, pushes that into the hidden field and replaces the input.value
with the innerText
.
document.querySelector('#answerInput').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option[value="'+input.value+'"]'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden');
if (options.length > 0) {
hiddenInput.value = input.value;
input.value = options[0].innerText;
}
});
As a consequence the user sees whatever the option's innerText
says, but the unique id from option.value
is available upon form submit.
Demo jsFiddle
The best you can do is import the dynamic library inside a bridging header:
#import <sqlite3.h>
to the topYou will then be able to access all of the c methods like sqlite3_open
from your swift code.
However, you may just want to use FMDB and import that through the bridging header as that is a more object oriented wrapper of sqlite. Dealing with C pointers and structs will be cumbersome in Swift.
EDIT: Sorry, I should have tested better before. This should work:
new File(new URI(androidURI.toString()));
URI is java.net.URI.
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
You could also use a third party api to do device detection via user agent string. One such service is www.useragentinfo.co. Just sign up and get your api token and below is how you get the device info via PHP:
<?php
$useragent = $_SERVER['HTTP_USER_AGENT'];
// get api token at https://www.useragentinfo.co/
$token = "<api-token>";
$url = "https://www.useragentinfo.co/api/v1/device/";
$data = array('useragent' => $useragent);
$headers = array();
$headers[] = "Content-type: application/json";
$headers[] = "Authorization: Token " . $token;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
echo $json_response;
?>
And here is the sample response if the visitor is using an iPhone:
{
"device_type":"SmartPhone",
"browser_version":"5.1",
"os":"iOS",
"os_version":"5.1",
"device_brand":"Apple",
"bot":false,
"browser":"Mobile Safari",
"device_model":"iPhone"
}
try
{
$tableAresults = $dbHandler->doSomethingWithTableA();
if(!tableAresults)
{
throw new Exception('Problem with tableAresults');
}
$tableBresults = $dbHandler->doSomethingElseWithTableB();
if(!tableBresults)
{
throw new Exception('Problem with tableBresults');
}
} catch (Exception $e)
{
echo $e->getMessage();
}
SQL Server
To list all the user defined tables of a database:
use [databasename]
select name from sysobjects where type = 'u'
To list all the columns of a table:
use [databasename]
select name from syscolumns where id=object_id('tablename')
Something like this?
<!DOCTYPE html>
<html>
<head>
<style>
form * {
display: block;
margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="name" value="test.txt">
<textarea rows=3 cols=50 name="text">Please type in this box. When you
click the Download button, the contents of this box will be downloaded to
your machine at the location you specify. Pretty nifty. </textarea>
<input type="submit" value="Download">
</form>
</body>
</html>
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
This will depend on the device you're using. If you're using a pdf device, you can do this:
pdf( "mygraph.pdf", width = 11, height = 8 )
plot( x, y )
You can then divide up the space in the pdf using the mfrow parameter like this:
par( mfrow = c(2,2) )
That makes a pdf with four panels available for plotting. Unfortunately, some of the devices take different units than others. For example, I think that X11 uses pixels, while I'm certain that pdf uses inches. If you'd just like to create several devices and plot different things to them, you can use dev.new(), dev.list(), and dev.next().
Other devices that might be useful include:
There's a list of all of the devices here.
This answer is for beginners (none-git gurus). I recently had this problem and maybe its just me but most of the answers seemed to require rather advance understanding of git. After reading several stack overflow answers including this thread, here are the steps I needed to take in order to easily switch between GitHub accounts (e.g. assume two GitHub accounts, github.com/personal and gitHub.com/work):
ls -al ~/.ssh
.pub
are your ssh keys so you should have two for the personal
and work
accounts. If there is only one or none, its time to generate other wise skip this.ssh-keygen -t rsa -C "the copied email"
, you'll see:/.../.ssh/id_rsa_work
if generating for work account. provide a password or just enter to ignore and, you'll read something like The key's randomart image is: and the image. done.ls -al ~/.ssh
again.pbcopy < ~/.ssh/id_rsa_work.pub
, replace id_rsa_work.pub
with what you called yours.id_rsa_work
] and navigate toEdit the global git configuration: Last step is to make sure the global configuration file is aware of all github accounts (so to say).
Run git config --global --edit
to edit this global file, if this opens vim and you don't know how to use it, press i
to enter Insert mode, edit the file as below, and press esc followed by :wq
to exit insert mode:
[inside this square brackets give a name to the followed acc.]
name = github_username
email = github_emailaddress
[any other name]
name = github_username
email = github_email
[credential]
helper = osxkeychain
useHttpPath = true
Done!, now when trying to push or pull from a repo, you'll be asked which GitHub account should be linked with this repo and its asked only once, the local configuration will remember this link and not the global configuration so you can work on different repos that are linked with different accounts without having to edit global configuration each time.
This is by far the easiest way to restart the current activity:
finish();
startActivity(getIntent());
Here is a simple filter pipe for array of objects that contain attributes with string values (ES6)
filter-array-pipe.js
import {Pipe} from 'angular2/core';
// # Filter Array of Objects
@Pipe({ name: 'filter' })
export class FilterArrayPipe {
transform(value, args) {
if (!args[0]) {
return value;
} else if (value) {
return value.filter(item => {
for (let key in item) {
if ((typeof item[key] === 'string' || item[key] instanceof String) &&
(item[key].indexOf(args[0]) !== -1)) {
return true;
}
}
});
}
}
}
Your component
myobjComponent.js
import {Component} from 'angular2/core';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {FilterArrayPipe} from 'filter-array-pipe';
@Component({
templateUrl: 'myobj.list.html',
providers: [HTTP_PROVIDERS],
pipes: [FilterArrayPipe]
})
export class MyObjList {
static get parameters() {
return [[Http]];
}
constructor(_http) {
_http.get('/api/myobj')
.map(res => res.json())
.subscribe(
data => this.myobjs = data,
err => this.logError(err))
);
}
resetQuery(){
this.query = '';
}
}
In your template
myobj.list.html
<input type="text" [(ngModel)]="query" placeholder="... filter" >
<div (click)="resetQuery()"> <span class="icon-cross"></span> </div>
</div>
<ul><li *ngFor="#myobj of myobjs| filter:query">...<li></ul>
You could use the following without the wrapper function, but it provides a nicer API:
Function IsInArray(ByVal findString as String, ByVal arrayToSearch as Variant) as Boolean
IsInArray = UBound(Filter(arrayToSearch,findString)) >= 0
End Function
The Filter
function has the following signature:
Filter(sourceArray, stringToMatch, [Include As Boolean = True], [Compare as VbCompareMethod = vbBinaryCompare])
For an example data in your table such as combinations of
''
, null
and as well as actual value
than if you want to only actual value
and replace to ''
and null
value by #
symbol than execute this query
SELECT Column_Name = (CASE WHEN (Column_Name IS NULL OR Column_Name = '') THEN '#' ELSE Column_Name END) FROM Table_Name
and another way you can use it but this is little bit lengthy and instead of this you can also use IsNull
function but here only i am mentioning IIF
function
SELECT IIF(Column_Name IS NULL, '#', Column_Name) FROM Table_Name
SELECT IIF(Column_Name = '', '#', Column_Name) FROM Table_Name
-- and syntax of this query
SELECT IIF(Column_Name IS NULL, 'True Value', 'False Value') FROM Table_Name
The ol, ul lists will work if you want you can also use a table with border: none in the css.
It's possible to redirect to another view with angular-ui-router. For this purpose, we have the method $state.go("target_view")
. For example:
---- app.js -----
var app = angular.module('myApp', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
// Otherwise
$urlRouterProvider.otherwise("/");
$stateProvider
// Index will decide if redirects to Login or Dashboard view
.state("index", {
url: ""
controller: 'index_controller'
})
.state('dashboard', {
url: "/dashboard",
controller: 'dashboard_controller',
templateUrl: "views/dashboard.html"
})
.state('login', {
url: "/login",
controller: 'login_controller',
templateUrl: "views/login.html"
});
});
// Associate the $state variable with $rootScope in order to use it with any controller
app.run(function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
});
app.controller('index_controller', function ($scope, $log) {
/* Check if the user is logged prior to use the next code */
if (!isLoggedUser) {
$log.log("user not logged, redirecting to Login view");
// Redirect to Login view
$scope.$state.go("login");
} else {
// Redirect to dashboard view
$scope.$state.go("dashboard");
}
});
----- HTML -----
<!DOCTYPE html>
<html>
<head>
<title>My WebSite</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="MyContent">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/libs/angular.min.js" type="text/javascript"></script>
<script src="js/libs/angular-ui-router.min.js" type="text/javascript"></script>
<script src="js/app.js" type="text/javascript"></script>
</head>
<body ng-app="myApp">
<div ui-view></div>
</body>
</html>
PHP - curl:
$username = 'myusername';
$password = 'mypassword';
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...
PHP - POST in WordPress:
$username = 'myusername';
$password = 'mypassword';
...
wp_remote_post('https://...some...api...endpoint...', array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode("$username:$password")
)
));
...
You can use
a.Except(b).Union(b.Except(a));
Or you can use
var difference = new HashSet(a);
difference.SymmetricExceptWith(b);
Here is another variant I posted on related question. The REGEX
check to see if you are out of bounds is useful, so for a table column you would put it in the where clause.
SET @Array = 'one,two,three,four';
SET @ArrayIndex = 2;
SELECT CASE
WHEN @Array REGEXP CONCAT('((,).*){',@ArrayIndex,'}')
THEN SUBSTRING_INDEX(SUBSTRING_INDEX(@Array,',',@ArrayIndex+1),',',-1)
ELSE NULL
END AS Result;
SUBSTRING_INDEX(string, delim, n)
returns the first nSUBSTRING_INDEX(string, delim, -1)
returns the last onlyREGEXP '((delim).*){n}'
checks if there are n delimiters (i.e. you are in bounds)This problem can be caused by requests for certain files that don't exist. For example, requests for files in wp-content/uploads/ where the file does not exist.
If this is the situation you're seeing, you can solve the problem by going to .htaccess and changing this line:
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
to:
RewriteRule ^(wp-(content|admin|includes).*) - [L]
The underlying issue is that the rule above triggers a rewrite to the exact same url with a slash in front and because there was a rewrite, the newly rewritten request goes back through the rules again and the same rule is triggered. By changing that line's "$1" to "-", no rewrite happens and so the rewriting process does not start over again with the same URL.
It's possible that there's a difference in how apache 2.2 and 2.4 handle this situation of only-difference-is-a-slash-in-front and that's why the default rules provided by WordPress aren't working perfectly.
For me the issue was that I was converting an existing project to maven, created the folder structures according to the documentation and it was showing the 'main' folder as part of the package. I followed the instructions similar to Jon Skeet / JWoodchuck and went into the Java build path, removed all broken build paths, and then added my build path to be 'src/main/java' and 'src/test/java', as well as the resources folders for each, and it resolved the issue.
You can remove the "bullets" by setting the "list-style-type: none;" Like
ul
{
list-style-type: none;
}
OR
<ul class="menu custompozition4" style="list-style-type: none;">
<li class="item-507"><a href=#">Strategic Recruitment Solutions</a>
</li>
<li class="item-508"><a href="#">Executive Recruitment</a>
</li>
<li class="item-509"><a href="#">Leadership Development</a>
</li>
<li class="item-510"><a href="#">Executive Capability Review</a>
</li>
<li class="item-511"><a href="#">Board and Executive Coaching</a>
</li>
<li class="item-512"><a href="#">Cross Cultutral Coaching</a>
</li>
<li class="item-513"><a href="#">Team Enhancement & Coaching</a>
</li>
<li class="item-514"><a href="#">Personnel Re-deployment</a>
</li>
</ul>
You have to cast it to a correct format Playground.
yourTime := rand.Int31n(1000)
time.Sleep(time.Duration(yourTime) * time.Millisecond)
If you will check documentation for sleep, you see that it requires func Sleep(d Duration)
duration as a parameter. Your rand.Int31n returns int32
.
The line from the example works (time.Sleep(100 * time.Millisecond)
) because the compiler is smart enough to understand that here your constant 100 means a duration. But if you pass a variable, you should cast it.
Alternatively YUI has http://yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify.
For example:
var data = { one: 'first', two: 'second' };
var result = Y.QueryString.stringify(data);
You need to update your all packages when you are move VS2015 to VS2017 for discover test in test explorer.
Try this if using spark 2.0+
For non-hdfs file:
df = spark.read.csv("file:///csvfile.csv")
For hdfs file:
df = spark.read.csv("hdfs:///csvfile.csv")
For hdfs file (with different delimiter than comma:
df = spark.read.option("delimiter","|")csv("hdfs:///csvfile.csv")
Note:- this work for any delimited file. Just use option(“delimiter”,) to change value.
Hope this is helpful.
If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount
property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).
If you cannot find it this way, try the menu: View/Properties Window.
Or try the F4 key.
I had the same issue on a remote windows environment. I tried many solutions found here or on other similars posts but nothing worked. Finally, the solution was quite simple. I had to set NO_PROXY
with cmd :
set NO_PROXY="<domain>\<username>:<password>@<host>:<port>"
pip install <packagename>
You have to use double quotes and set NO_PROXY
to upper case. You can also add NO_PROXY
as an environment variable instead of setting it each time you use the console.
I hope this will help if any other solution posted here works.
Since data.table
1.12.4 (Oct 2019), data.table
gains two functions to facilitate this: nafill
and setnafill
.
nafill
operates on columns:
cols = c('a', 'b')
y[ , (cols) := lapply(.SD, nafill, fill=0), .SDcols = cols]
setnafill
operates on tables (the replacements happen by-reference/in-place)
setnafill(y, cols=cols, fill=0)
# print y to show the effect
y[]
This will also be more efficient than the other options; see ?nafill
for more, the last-observation-carried-forward (LOCF) and next-observation-carried-backward (NOCB) versions of NA
imputation for time series.
This will work for your data.table
version:
for (col in c("a", "b")) y[is.na(get(col)), (col) := 0]
Alternatively, as David Arenburg points out below, you can use set
(side benefit - you can use it either on data.frame
or data.table
):
for (col in 1:2) set(x, which(is.na(x[[col]])), col, 0)
(Edited: wasn't aware of the `naked link' problem, sorry about that)
Taken from here:
string myString = "find Me and replace ME";
string strReplace = "me";
myString = Regex.Replace(myString, "me", strReplace, RegexOptions.IgnoreCase);
Seems you are not the first to complain of the lack of case insensitive string.Replace.
It happens when there is no runnable module for Android App in your project. Creating new project definitely solves this.
You can check this using Run > Edit Configurations > Adding Android App
. If there is not runnable Android App module then you can't see "AVD Manager" in the menu.
Hey i figured it out shortly after. For some reason I was just having a brain fart.
image.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.2)
I have calculated the formula below to make the conversions dpi
to dp
and sp
The second option really isn't the same as the others - if the string is "///foo" it will become "foo" instead of "//foo".
The first option needs a bit more work to understand than the third - I would view the Substring
option as the most common and readable.
(Obviously each of them as an individual statement won't do anything useful - you'll need to assign the result to a variable, possibly data
itself.)
I wouldn't take performance into consideration here unless it was actually becoming a problem for you - in which case the only way you'd know would be to have test cases, and then it's easy to just run those test cases for each option and compare the results. I'd expect Substring
to probably be the fastest here, simply because Substring
always ends up creating a string from a single chunk of the original input, whereas Remove
has to at least potentially glue together a start chunk and an end chunk.
You can use the following for an awk solution -
awk '/^#/ {sub(/#.*/,"");getline;}1' inputfile
UK Government Data Standards Catalogue details the UK standards for this kind of thing. It suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name, and 255 characters for an email address. Amongst other things..
I've been using:
@media only screen and (min-width: 768px) {
/* tablets and desktop */
}
@media only screen and (max-width: 767px) {
/* phones */
}
@media only screen and (max-width: 767px) and (orientation: portrait) {
/* portrait phones */
}
It keeps things relatively simple and allows you to do something a bit different for phones in portrait mode (a lot of the time I find myself having to change various elements for them).
You can use Jquery's on method and listen for the scroll
event.
untested, but in my mind, this should work? cause it'll be 0x01 on little endian, and 0x00 on big endian?
bool runtimeIsLittleEndian(void)
{
volatile uint16_t i=1;
return ((uint8_t*)&i)[0]==0x01;//0x01=little, 0x00=big
}
You can read in the data as chunks and save each chunk as pickle.
import pandas as pd
import pickle
in_path = "" #Path where the large file is
out_path = "" #Path to save the pickle files to
chunk_size = 400000 #size of chunks relies on your available memory
separator = "~"
reader = pd.read_csv(in_path,sep=separator,chunksize=chunk_size,
low_memory=False)
for i, chunk in enumerate(reader):
out_file = out_path + "/data_{}.pkl".format(i+1)
with open(out_file, "wb") as f:
pickle.dump(chunk,f,pickle.HIGHEST_PROTOCOL)
In the next step you read in the pickles and append each pickle to your desired dataframe.
import glob
pickle_path = "" #Same Path as out_path i.e. where the pickle files are
data_p_files=[]
for name in glob.glob(pickle_path + "/data_*.pkl"):
data_p_files.append(name)
df = pd.DataFrame([])
for i in range(len(data_p_files)):
df = df.append(pd.read_pickle(data_p_files[i]),ignore_index=True)
find /the_path_you_want_to_find -name index.html
No need for "tricks". Python 3.3 comes with PyLauncher "py.exe", installs it in the path, and registers it as the ".py" extension handler. With it, a special comment at the top of a script tells the launcher which version of Python to run:
#!python2
print "hello"
Or
#!python3
print("hello")
From the command line:
py -3 hello.py
Or
py -2 hello.py
py hello.py
by itself will choose the latest Python installed, or consult the PY_PYTHON
environment variable, e.g. set PY_PYTHON=3.6
.
It is sure because the Invoke-WebRequest command has a dependency on the Internet Explorer assemblies and are invoking it to parse the result as per default behaviour. As Matt suggest, you can simply launch IE and make your selection in the settings prompt which is popping up at first launch. And the error you experience will disappear.
But this is only possible if you run your powershell scripts as the same windows user as whom you launched the IE with. The IE settings are stored under your current windows profile. So if you, like me run your task in a scheduler on a server as the SYSTEM user, this will not work.
So here you will have to change your scripts and add the -UseBasicParsing argument, as ijn this example: $WebResponse = Invoke-WebRequest -Uri $url -TimeoutSec 1800 -ErrorAction:Stop -Method:Post -Headers $headers -UseBasicParsing
It sounds like you want to convert the rownames to a proper column of the data.frame. eg:
# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF
# Row.Names id val vr2
# row_one row_one A 1 23
# row_two row_two A 2 24
# row_three row_three B 3 25
# row_four row_four C 4 26
If you want to then remove the original rownames:
rownames(myDF) <- NULL
myDF
# Row.Names id val vr2
# 1 row_one A 1 23
# 2 row_two A 2 24
# 3 row_three B 3 25
# 4 row_four C 4 26
Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames
myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat
# Names.of.Rows id val vr2
# row_one "A" "1" "23"
# row_two "A" "2" "24"
# row_three "B" "3" "25"
# row_four "C" "4" "26"
I am using below code for the iOS 9 and its working fine for me. I have also use shadow color for the title.
self.navigationItem.title = @"MY NAV TITLE";
self.navigationController.navigationBar.barTintColor = [UIColor redColor];
self.navigationController.navigationBar.translucent = NO;
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
shadow.shadowOffset = CGSizeMake(0, 1);
[self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], NSForegroundColorAttributeName,
shadow, NSShadowAttributeName,
[UIFont fontWithName:@"HelveticaNeue-Light" size:21.0], NSFontAttributeName, nil]];
May this help you.
Thanks
Step 1: open your mysql workbench application select table. choose image cell right click select "Open value in Editor"
Step 2: click on the load button and choose image file
Step 3:then click apply button
Step 4: Then apply the query to save the image .Don't forgot image data type is "BLOB". Step 5: You can can check uploaded image
please refer to this post for the changes in ruby1.9 Getting an ASCII character code in Ruby using `?` (question mark) fails
Why not use outline? it is what you want outline:1px solid red;
i think this will help you
content of .htaccess
ErrorDocument 404 /error.php
ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 405 /error.php
ErrorDocument 406 /error.php
ErrorDocument 409 /error.php
ErrorDocument 413 /error.php
ErrorDocument 414 /error.php
ErrorDocument 500 /error.php
ErrorDocument 501 /error.php
error.php and .htaccess should be put in the same directory [in this case]
Simply add static
in the declaration of these two methods and the compile time error will disappear!
By default in C# methods are instance methods, and they receive the implicit "self" argument. By making them static, no such argument is needed (nor available), and the method must then of course refrain from accessing any instance (non-static) objects or methods of the class.
More info on static methods
Provided the class and the method's access modifiers (public vs. private) are ok, a static method can then be called from anywhere without having to previously instantiate a instance of the class. In other words static methods are used with the following syntax:
className.classMethod(arguments)
rather than
someInstanceVariable.classMethod(arguments)
A classical example of static methods are found in the System.Math class, whereby we can call a bunch of these methods like
Math.Sqrt(2)
Math.Cos(Math.PI)
without ever instantiating a "Math" class (in fact I don't even know if such an instance is possible)
As mentioned in a comment (and another answer as I typed) you need to register an event handler to catch the keydown or keypress event on a text box. This is because TextChanged is only fired when the TextBox loses focus
The below regex lets you match those characters you want to allow
Regex regex = new Regex(@"[0-9+\-\/\*\(\)]");
MatchCollection matches = regex.Matches(textValue);
and this does the opposite and catches characters that aren't allowed
Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textValue);
I'm not assuming there'll be a single match as someone could paste text into the textbox. in which case catch textchanged
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
private void textBox1_TextChanged(object sender, EventArgs e)
{
Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textBox1.Text);
if (matches.Count > 0) {
//tell the user
}
}
and to validate single key presses
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for a naughty character in the KeyDown event.
if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9^+^\-^\/^\*^\(^\)]"))
{
// Stop the character from being entered into the control since it is illegal.
e.Handled = true;
}
}
I got this error by referencing an enum which was imported in a wrong way, e.g.:
from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member
Correct import:
from package.MyEnumClass import MyEnumClass
Hope that helps someone
As reported by Tim Anderson
Cross-platform development is a big deal, and will continue to be so until a day comes when everyone uses the same platform. Android? HTML? WebKit? iOS? Windows? Xamarin? Titanum? PhoneGap? Corona? ecc.
Sometimes I hear it said that there are essentially two approaches to cross-platform mobile apps. You can either use an embedded browser control and write a web app wrapped as a native app, as in Adobe PhoneGap/Cordova or the similar approach taken by Sencha, or you can use a cross-platform tool that creates native apps, such as Xamarin Studio, Appcelerator Titanium, or Embarcardero FireMonkey.
Within the second category though, there is diversity. In particular, they vary concerning the extent to which they abstract the user interface.
Here is the trade-off. If you design your cross-platform framework you can have your application work almost the same way on every platform. If you are sharing the UI design across all platforms, it is hard to make your design feel equally right in all cases. It might be better to take the approach adopted by most games, using a design that is distinctive to your app and make a virtue of its consistency across platforms, even though it does not have the native look and feel on any platform.
edit Xamarin v3 in 2014 started offering choice of Xamarin.Forms as well as pure native that still follows the philosophy mentioned here (took liberty of inline edit because such a great answer)
Xamarin Studio on the other hand makes no attempt to provide a shared GUI framework:
We don’t try to provide a user interface abstraction layer that works across all the platforms. We think that’s a bad approach that leads to lowest common denominator user interfaces. (Nat Friedman to Tim Anderson)
This is right; but the downside is the effort involved in maintaining two or more user interface designs for your app.
Comparison about PhoneGap and Titanium it's well reported in Kevin Whinnery blog.
The purpose of PhoneGap is to allow HTML-based web applications to be deployed and installed as native applications. PhoneGap web applications are wrapped in a native application shell, and can be installed via the native app stores for multiple platforms. Additionally, PhoneGap strives to provide a common native API set which is typically unavailable to web applications, such as basic camera access, device contacts, and sensors not already exposed in the browser.
To develop PhoneGap applications, developers will create HTML, CSS, and JavaScript files in a local directory, much like developing a static website. Approaching native-quality UI performance in the browser is a non-trivial task - Sencha employs a large team of web programming experts dedicated full-time to solving this problem. Even so, on most platforms, in most browsers today, reaching native-quality UI performance and responsiveness is simply not possible, even with a framework as advanced as Sencha Touch. Is the browser already “good enough” though? It depends on your requirements and sensibilities, but it is unquestionably less good than native UI. Sometimes much worse, depending on the browser.
PhoneGap is not as truly cross-platform as one might believe, not all features are equally supported on all platforms.
Javascript is not an application scale programming language, too many global scope interactions, different libraries don't often co-exist nicely. We spent many hours trying to get knockout.js and jQuery.mobile play well together, and we still have problems.
Fragmented landscape for frameworks and libraries. Too many choices, and too many are not mature enough.
Strangely enough, for the needs of our app, decent performance could be achieved (not with jQuery.Mobile, though). We tried jqMobi (not very mature, but fast).
Very limited capability for interaction with other apps or cdevice capabilities, and this would not be cross-platform anyway, as there aren't any standards in HTML5 except for a few, like geolocation, camera and local databases.
The goal of Titanium Mobile is to provide a high level, cross-platform JavaScript runtime and API for mobile development (today we support iOS, Android and Windows Phone. Titanium actually has more in common with MacRuby/Hot Cocoa, PHP, or node.js than it does with PhoneGap, Adobe AIR, Corona, or Rhomobile. Titanium is built on two assertions about mobile development: - There is a core of mobile development APIs which can be normalized across platforms. These areas should be targeted for code reuse. - There are platform-specific APIs, UI conventions, and features which developers should incorporate when developing for that platform. Platform-specific code should exist for these use cases to provide the best possible experience.
So for those reasons, Titanium is not an attempt at “write once, run everywhere”. Same as Xamarin.
Titanium are going to do a further step in the direction similar to that of Xamarin. In practice, they will do two layers of different depths: the layer Titanium (in JS), which gives you a bee JS-of-Titanium. If you want to go more low-level, have created an additional layer (called Hyperloop), where (always with JS) to call you back directly to native APIs of SO
Xamarin (originally a division of Novell) in the last 18 months has brought to market its own IDE and snap-in for Visual Studio. The underlining premise of Mono is to create disparate mobile applications using C# while maintaining native UI development strategies.
In addition to creating a visual design platform to develop native applications, they have integrated testing suites, incorporated native library support and a Nuget style component store. Recently they provided iOS visual design through their IDE freeing the developer from opening XCode. In Visual Studio all three platforms are now supported and a cloud testing suite is on the horizon.
From the get go, Xamarin has provided a rich Android visual design experience. I have yet to download or open Eclipse or any other IDE besides Xamarin. What is truly amazing is that I am able to use LINQ to work with collections as well as create custom delegates and events that free me from objective-C and Java limitations. Many of the libraries I have been spoiled with, like Newtonsoft JSON.Net, work perfectly in all three environments.
In my opinion there are several HUGE advantages including
Upgrade for me is use Xamarin and MVVMCross combined. It's still quite a new framework, but it's born from experience of several other frameworks (such as MvvmLight and monocross) and it's now been used in at several released cross platform projects.
My choice after knowing all these framwework, was to select development tool based on product needs. In general, however if you start to use a tool with which you feel comfortable (even if it requires a higher initial overhead) after you'll use it forever.
I chose Xamarin + MVVMCross and I must say to be happy with this choice. I'm not afraid of approach Native SDK for software updates or seeing limited functionality of a system or the most trivial thing a feature graphics. Write code fairly structured (DDD + SOA) is very useful to have a core project shared with native C# views implementation.
You can access columns by index, by name and some other ways:
dtResult.Rows(i)("columnName") = strVerse
You should probably make sure your DataTable
has some columns first...
In my case, I had accidentally named a folder 'samples '. I couldn't see the space when I did 'ls -la'.
Eventually I realized this when I tried tabbing to autocomplete and saw 'samples\ /'.
To fix this I ran
mv samples\ samples
$(document).height() //returns window height
$(document).scrollTop() //returns scroll position from top of document
First off I recommend you use the following constructor instead of the one you currently use:
new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One);
Next, you really should remove this code:
// Wait 10 Seconds for data...
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(10);
Console.WriteLine(sp.Read(buf,0,bufSize)); //prints data directly to the Console
}
And instead just loop until the user presses a key or something, like so:
namespace serialPortCollection
{ class Program
{
static void Main(string[] args)
{
SerialPort sp = new SerialPort("COM10", 115200);
sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler
sp.Open();
sp.WriteLine("$"); //Command to start Data Stream
Console.ReadLine();
sp.WriteLine("!"); //Stop Data Stream Command
sp.Close();
}
// My Event Handler Method
private static void port_OnReceiveDatazz(object sender,
SerialDataReceivedEventArgs e)
{
SerialPort spL = (SerialPort) sender;
byte[] buf = new byte[spL.BytesToRead];
Console.WriteLine("DATA RECEIVED!");
spL.Read(buf, 0, buf.Length);
foreach (Byte b in buf)
{
Console.Write(b.ToString());
}
Console.WriteLine();
}
}
}
Also, note the revisions to the data received event handler, it should actually print the buffer now.
UPDATE 1
I just ran the following code successfully on my machine (using a null modem cable between COM33 and COM34)
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Thread writeThread = new Thread(new ThreadStart(WriteThread));
SerialPort sp = new SerialPort("COM33", 115200, Parity.None, 8, StopBits.One);
sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler
sp.Open();
sp.WriteLine("$"); //Command to start Data Stream
writeThread.Start();
Console.ReadLine();
sp.WriteLine("!"); //Stop Data Stream Command
sp.Close();
}
private static void port_OnReceiveDatazz(object sender,
SerialDataReceivedEventArgs e)
{
SerialPort spL = (SerialPort) sender;
byte[] buf = new byte[spL.BytesToRead];
Console.WriteLine("DATA RECEIVED!");
spL.Read(buf, 0, buf.Length);
foreach (Byte b in buf)
{
Console.Write(b.ToString() + " ");
}
Console.WriteLine();
}
private static void WriteThread()
{
SerialPort sp2 = new SerialPort("COM34", 115200, Parity.None, 8, StopBits.One);
sp2.Open();
byte[] buf = new byte[100];
for (byte i = 0; i < 100; i++)
{
buf[i] = i;
}
sp2.Write(buf, 0, buf.Length);
sp2.Close();
}
}
}
UPDATE 2
Given all of the traffic on this question recently. I'm beginning to suspect that either your serial port is not configured properly, or that the device is not responding.
I highly recommend you attempt to communicate with the device using some other means (I use hyperterminal frequently). You can then play around with all of these settings (bitrate, parity, data bits, stop bits, flow control) until you find the set that works. The documentation for the device should also specify these settings. Once I figured those out, I would make sure my .NET SerialPort is configured properly to use those settings.
Some tips on configuring the serial port:
Note that when I said you should use the following constructor, I meant that use that function, not necessarily those parameters! You should fill in the parameters for your device, the settings below are common, but may be different for your device.
new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One);
It is also important that you setup the .NET SerialPort to use the same flow control as your device (as other people have stated earlier). You can find more info here:
http://www.lammertbies.nl/comm/info/RS-232_flow_control.html
There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD
so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:
import java.time.Instant;
public static void main(String[] args) {
String date="2010-10-02T12:23:23Z";
try {
Instant myDate = Instant.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I did not need it, but as getting year is in code from the question, then:
it is trickier, cannot be done from Instant
directly, can be done via Calendar
in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:
myDate.toString().substring(0,4);
name()
is a "built-in" method of enum
. It is final and you cannot change its implementation. It returns the name of enum constant as it is written, e.g. in upper case, without spaces etc.
Compare MOBILE_PHONE_NUMBER
and Mobile phone number
. Which version is more readable? I believe the second one. This is the difference: name()
always returns MOBILE_PHONE_NUMBER
, toString()
may be overriden to return Mobile phone number
.
If you are using PHP, just use the addslashes() function.
Let's think a little different, You can use static parameters:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function func() {
echo global::$foo;
}