Connection Java-MySql : Public Key Retrieval is not allowed
Alternatively to the suggested answers you could try and use mysql_native_password authentication plugin instead of caching_sha2_password authentication plugin.
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_password_here';
React navigation goBack() and update parent state
You can pass a callback function as parameter when you call navigate like this:
const DEMO_TOKEN = await AsyncStorage.getItem('id_token');
if (DEMO_TOKEN === null) {
this.props.navigation.navigate('Login', {
onGoBack: () => this.refresh(),
});
return -3;
} else {
this.doSomething();
}
And define your callback function:
refresh() {
this.doSomething();
}
Then in the login/registration view, before goBack, you can do this:
await AsyncStorage.setItem('id_token', myId);
this.props.navigation.state.params.onGoBack();
this.props.navigation.goBack();
Update for React Navigation v5:
await AsyncStorage.setItem('id_token', myId);
this.props.route.params.onGoBack();
this.props.navigation.goBack();
Registering for Push Notifications in Xcode 8/Swift 3.0?
I had issues with the answers here in converting the deviceToken Data object to a string to send to my server with the current beta of Xcode 8. Especially the one that was using deviceToken.description as in 8.0b6 that would return "32 Bytes" which isn't very useful :)
This is what worked for me...
Create an extension on Data to implement a "hexString" method:
extension Data {
func hexString() -> String {
return self.reduce("") { string, byte in
string + String(format: "%02X", byte)
}
}
}
And then use that when you receive the callback from registering for remote notifications:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.hexString()
// Send to your server here...
}
How to detect Esc Key Press in React and how to handle it
For a reusable React hook solution
import React, { useEffect } from 'react';
const useEscape = (onEscape) => {
useEffect(() => {
const handleEsc = (event) => {
if (event.keyCode === 27)
onEscape();
};
window.addEventListener('keydown', handleEsc);
return () => {
window.removeEventListener('keydown', handleEsc);
};
}, []);
}
export default useEscape
Usage:
const [isOpen, setIsOpen] = useState(false);
useEscape(() => setIsOpen(false))
How to configure CORS in a Spring Boot + Spring Security application?
I solved this problem by:
`
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers","Access-Control-Allow-Origin","Access-Control-Request-Method", "Access-Control-Request-Headers","Origin","Cache-Control", "Content-Type", "Authorization"));
configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
`
Spark: Add column to dataframe conditionally
My bad, I had missed one part of the question.
Best, cleanest way is to use a UDF
.
Explanation within the code.
// create some example data...BY DataFrame
// note, third record has an empty string
case class Stuff(a:String,b:Int)
val d= sc.parallelize(Seq( ("a",1),("b",2),
("",3) ,("d",4)).map { x => Stuff(x._1,x._2) }).toDF
// now the good stuff.
import org.apache.spark.sql.functions.udf
// function that returns 0 is string empty
val func = udf( (s:String) => if(s.isEmpty) 0 else 1 )
// create new dataframe with added column named "notempty"
val r = d.select( $"a", $"b", func($"a").as("notempty") )
scala> r.show
+---+---+--------+
| a| b|notempty|
+---+---+--------+
| a| 1| 1111|
| b| 2| 1111|
| | 3| 0|
| d| 4| 1111|
+---+---+--------+
How to stop INFO messages displaying on spark console?
If anyone else is stuck on this,
nothing of the above worked for me.
I had to remove
implementation group: "ch.qos.logback", name: "logback-classic", version: "1.2.3"
implementation group: 'com.typesafe.scala-logging', name: "scala-logging_$scalaVersion", version: '3.9.2'
from my build.gradle for the logs to disappear. TLDR: Don't import any other logging frameworks, you should be fine just using org.apache.log4j.Logger
Classpath resource not found when running as jar
If you want to use a file:
ClassPathResource classPathResource = new ClassPathResource("static/something.txt");
InputStream inputStream = classPathResource.getInputStream();
File somethingFile = File.createTempFile("test", ".txt");
try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
IOUtils.closeQuietly(inputStream);
}
Spring Boot application.properties value not populating
The way you are performing the injection of the property will not work, because the injection is done after the constructor is called.
You need to do one of the following:
Better solution
@Component
public class MyBean {
private final String prop;
@Autowired
public MyBean(@Value("${some.prop}") String prop) {
this.prop = prop;
System.out.println("================== " + prop + "================== ");
}
}
Solution that will work but is less testable and slightly less readable
@Component
public class MyBean {
@Value("${some.prop}")
private String prop;
public MyBean() {
}
@PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Also note that is not Spring Boot specific but applies to any Spring application
Why does my Spring Boot App always shutdown immediately after starting?
Here is how you can fix it:
Check if you don't have dependency on spring-boot-starter-web in your pom.xml file. To get you pom.xml file right, use this link start.spring.io
If you have above dependency, but still facing the issue, it is highly possible that your embedded tomcat jars are present.
To confirm this, run maven build in debug mode -
mvn spring-boot:run --debug
and look for messages like -
[WARNING] error reading
/Users/sparrowmac1/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.5.20/tomcat-embed-core-8.5.20.jar;
invalid LOC header (bad signature) [WARNING] error reading
/Users/sparrowmac1/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.8.10/jackson-core-2.8.10.jar;
invalid LOC header (bad signature)
If such messages are present, purge your local maven repo and try again -
mvn dependency:purge-local-repository
In Laravel, the best way to pass different types of flash messages in the session
Simply return with the 'flag' that you want to be treated without using any additional user function.
The Controller:
return \Redirect::back()->withSuccess( 'Message you want show in View' );
Notice that I used the 'Success' flag.
The View:
@if( Session::has( 'success' ))
{{ Session::get( 'success' ) }}
@elseif( Session::has( 'warning' ))
{{ Session::get( 'warning' ) }} <!-- here to 'withWarning()' -->
@endif
Yes, it really works!
Failed to instantiate module error in Angular js
Or the minified version of the file...
<script src="angular-route.min.js"></script>
More information about this here:
"This error occurs when a module fails to load due to some exception. The error message above should provide additional context."
"In AngularJS 1.2.0 and later, ngRoute has been moved to its own module. If you are getting this error after upgrading to 1.2.x, be sure that you've installed ngRoute."
Listed under section Error: $injector:modulerr Module Error
in the Angularjs docs.
How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
- Just extract the .ocx file from the .cab file (it is similar to a zip)
- Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
- Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")
References
jQuery click events not working in iOS
Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.
Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):
onClick=""
OR
The element css needs to have the following declaration:
cursor:pointer
Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working
Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?
In my case, I was getting this error despite registering an existing instance for the interface in question.
Turned out, it was because I was using Unity in WebForms by way of the Unity.WebForms Nuget package, and I had specified a Hierarchical Lifetime manager for the dependency I was providing an instance for, yet a Transient lifetime manager for a subsequent type that depended on the previous type - not usually an issue - but with Unity.WebForms, the lifetime managers work a little differently... your injected types seem to require a Hierarchical lifetime manager, but a new container is still created for every web request (because of the architecture of web forms I guess) as explained excellently in this post.
Anyway, I resolved it by simply not specifying a lifetime manager for the types/instances when registering them.
i.e.
container.RegisterInstance<IMapper>(MappingConfig.GetMapper(), new HierarchicalLifetimeManager());
container.RegisterType<IUserContext, UserContext>(new TransientLifetimeManager());
becomes
container.RegisterInstance<IMapper>(MappingConfig.GetMapper());
container.RegisterType<IUserContext, UserContext>();
So that IMapper can be resolved successfully here:
public class UserContext : BaseContext, IUserContext
{
public UserContext(IMapper _mapper) : base(_mapper)
{
}
...
}
PHP - Notice: Undefined index:
How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.
The module was expected to contain an assembly manifest
Check if the manifest is a valid xml file. I had the same problem by doing a DOS copy command at the end of the build, and it turns out that for some reason I can not understand "copy" was adding a strange character (->) at the end of the manifest files. The problem was solved by adding "/b" switch to force binary copy.
Detecting iOS orientation change instantly
Add a notifier in the viewWillAppear
function
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
The orientation change notifies this function
- (void)orientationChanged:(NSNotification *)notification{
[self adjustViewsForOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
}
which in-turn calls this function where the moviePlayerController frame is orientation is handled
- (void) adjustViewsForOrientation:(UIInterfaceOrientation) orientation {
switch (orientation)
{
case UIInterfaceOrientationPortrait:
case UIInterfaceOrientationPortraitUpsideDown:
{
//load the portrait view
}
break;
case UIInterfaceOrientationLandscapeLeft:
case UIInterfaceOrientationLandscapeRight:
{
//load the landscape view
}
break;
case UIInterfaceOrientationUnknown:break;
}
}
in viewDidDisappear
remove the notification
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}
I guess this is the fastest u can have changed the view as per orientation
IIS 7, HttpHandler and HTTP Error 500.21
Luckily, it’s very easy to resolve. Run the follow command from an elevated command prompt:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
If you’re on a 32-bit machine, you may have to use the following:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
I had a similar problem, but the differemce was: I didn't executed my JavaApp from localhost
, but from a remote PC. So I got something like java.sql.SQLException: Access denied for user 'root'@'a.remote.ip.adress' (using password: YES)
To solve this, you can simply login to phpMyAdmin, go to Users
, click add user
and enter the host from which you want to execute your JavaApp (or choose Any Host
)
Are email addresses case sensitive?
From RFC 5321, section 2.3.11:
The standard mailbox naming convention is defined to be
"local-part@domain"; contemporary usage permits a much broader set of
applications than simple "user names". Consequently, and due to a
long history of problems when intermediate hosts have attempted to
optimize transport by modifying them, the local-part MUST be
interpreted and assigned semantics only by the host specified in the
domain part of the address.
So yes, the part before the "@" could be case-sensitive, since it is entirely under the control of the host system. In practice though, no widely used mail systems distinguish different addresses based on case.
The part after the @ sign however is the domain and according to RFC 1035, section 3.1,
"Name servers and resolvers must compare [domains] in a case-insensitive manner"
In short, you are safe to treat email addresses as case-insensitive.
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
Get device token for push notification
In a build setting set code signing Provision Profile if you have APN Enable certificate then you will definitely get the token id. and remove
Provision Profile : Automatic
and set to
Provision Profile : Your provision profile certificate.
Detecting a long press with Android
When you mean user presses, do you mean a click? A click is when the user presses down and then immediately lifts up finger. Therefore it is encompassing two onTouch Events. You should save the use of onTouchEvent for stuff that happens on the initial touch or the after release.
Thus, you should be using onClickListener if it is a click.
Your answer is analogous: Use onLongClickListener.
Accessing the logged-in user in a template
You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user
.
Now, you can access every property of the user. For example, you can access the username like that : app.user.username
.
Warning, if the user is not logged, the app.user
is null.
If you want to check if the user is logged, you can use the is_granted
twig function. For example, if you want to check if the user has ROLE_ADMIN
, you just have to do is_granted("ROLE_ADMIN")
.
So, in every of your pages you can do :
{% if is_granted("ROLE") %}
Hi {{ app.user.username }}
{% endif %}
Android app unable to start activity componentinfo
The question is answered already, but I want add more information about the causes.
Android app unable to start activity componentinfo
This error often comes with appropriate logs. You can read logs and can solve this issue easily.
Here is a sample log. In which you can see clearly ClassCastException
. So this issue came because TextView
cannot be cast to EditText
.
Caused by: java.lang.ClassCastException: android.widget.TextView
cannot be cast to android.widget.EditText
11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050): at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050): ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109): at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109): ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167): at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167): ... 11 more
Some Common Mistakes.
1.findViewById()
of non existing view
Like when you use findViewById(R.id.button)
when button id does not exist in layout XML.
2. Wrong cast.
If you wrong cast some class, then you get this error. Like you cast RelativeLayout
to LinearLayout
or EditText
to TextView
.
3. Activity not registered in manifest.xml
If you did not register Activity in manifest.xml
then this error comes.
4. findViewById()
with declaration at top level
Below code is incorrect. This will create error. Because you should do findViewById()
after calling setContentView()
. Because an View can be there after it is created.
public class MainActivity extends Activity {
ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
//...
}
}
5. Starting abstract
Activity class.
When you try to start an Activity which is abstract, you will will get this error. So just remove abstract
keyword before activity class name.
6. Using kotlin but kotlin not configured.
If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.
More information
Read about Downcast and Upcast
Read about findViewById()
method of Activity class
Super keyword in Java
How to register activity in manifest
Solving a "communications link failure" with JDBC and MySQL
I know this is an old thread but I have tried numerous things and fixed my issue using the following means..
I'm developing a cross platform app on Windows but to be used on Linux and Windows servers.
A MySQL database called "jtm" installed on both systems. For some reason, in my code I had the database name as "JTM". On Windows it worked fine, in fact on several Windows systems it flew along.
On Ubuntu I got the error above time and time again. I tested it out with the correct case in the code "jtm" and it works a treat.
Linux is obviously a lot less forgiving about case sensitivity (rightly so), whereas Windows makes allowances.
I feel a bit daft now but check everything. The error message is not the best but it does seem fixable if you persevere and get things right.
Get Context in a Service
Since Service
is a Context
, the variable context must be this
:
DataBaseManager dbm = Utils.getDataManager(this);
Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)
I googled a lot but did not find a definite answer to my problem. I used KeyPass to generate a strong password and could use it successfully on mysql workbench to connect but not from the command line. So I changed the psw to an easy one and it worked on the command line. I have managed to create a strong password that was able to connect from the terminal. So my advise is, try with an easy password first before trying all kind of things.
Test iOS app on device without apple developer program or jailbreak
There's a way you can do this.
You will need ROOT access to edit the following file.
Navigate to /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk
and open the file SDKSettings.plist
.
In that file, expand DefaultProperties and change CODE_SIGNING_REQUIRED to NO
, while you are there, you can also change ENTITLEMENTS_REQUIRED to NO
also.
You will have to restart Xcode for the changes to take effect. Also, you must do this for every .sdk you want to be able to run on device.
Now, in your project settings, you can change Code Signing Identity
to Don't Code Sign
.
Your app should now build and install on your device successfully.
UPDATE:
There are some issues with iOS 5.1 SDK that this method may not work exactly the same. Any other updates will be listed here when they become available.
UPDATE:
You can find the correct path to SDKSettings.plist
with xcrun
.
xcrun --sdk iphoneos --show-sdk-path
New SDKSettings.plist location for the iOS 5.1 SDK:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/SDKSettings.plist
How do I get the serial key for Visual Studio Express?
I believe that if you download the offline ISO image file, and use that to install Visual Studio Express, you won't have to register.
Go here and find the link that says "All - Offline Install ISO image file". Click on it to expand it, select your language, and then click "Download".
Otherwise, it's possible that online registration is simply down for a while, as the error message indicates. You have 30 days before it expires, so give it a few days before starting to panic.
Android - SMS Broadcast receiver
android.provider.telephony.SMS_RECEIVED
is not correct because Telephony is a class and it should be capital as in android.provider.Telephony.SMS_RECEIVED
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
In my case, I faced this error when trying to connect to mysql-server running inside a container on a Ubuntu host VM from the same host.
Example:
If my VM name is abc.company.com
, the following jdbc URL would not work:
jdbc:mysql://abc.company.com:3306/dbname
Above jdbc url would work fine from other machines like xyz.company.com
but just not abc.company.com
.
where as the following jdbc URL would work just fine on abc.company.com
machine:
jdbc:mysql://localhost:3306/dbname
which led me to check the /etc/hosts
file.
Adding the following line to /etc/hosts
fixed this issue:
127.0.1.1 abc.company.com abc
This seems to be an OS bug that requires us to add these on some Ubuntu versions.
Reference: https://www.debian.org/doc/manuals/debian-reference/ch05.en.html#_the_hostname_resolution
Before trying this, I had tried all other solutions like GRANT ALL..
, changing the bind-address
line in mysql.cnf.. None of them helped me in this case.
How do I associate file types with an iPhone application?
BIG WARNING: Make ONE HUNDRED PERCENT sure that your extension is not already tied to some mime type.
We used the extension '.icz' for our custom files for, basically, ever, and Safari just never would let you open them saying "Safari cannot open this file." no matter what we did or tried with the UT stuff above.
Eventually I realized that there are some UT* C functions you can use to explore various things, and while .icz gives the right answer (our app):
In app did load at top, just do this...
NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,
(CFStringRef)@"icz",
NULL);
CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);
and put break after that line and see what UTI and ur are -- in our case, it was our identifier as we wanted), and the bundle url (ur) was pointing to our app's folder.
But the MIME type that Dropbox gives us back for our link, which you can check by doing e.g.
$ curl -D headers THEURLGOESHERE > /dev/null
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 27393 100 27393 0 0 24983 0 0:00:01 0:00:01 --:--:-- 28926
$ cat headers
HTTP/1.1 200 OK
accept-ranges: bytes
cache-control: max-age=0
content-disposition: attachment; filename="123.icz"
Content-Type: text/calendar
Date: Fri, 24 May 2013 17:41:28 GMT
etag: 872926d
pragma: public
Server: nginx
x-dropbox-request-id: 13bd327248d90fde
X-RequestId: bf9adc56934eff0bfb68a01d526eba1f
x-server-response-time: 379
Content-Length: 27393
Connection: keep-alive
The Content-Type is what we want. Dropbox claims this is a text/calendar entry. Great. But in my case, I've ALREADY TRIED PUTTING text/calendar into my app's mime types, and it still doesn't work. Instead, when I try to get the UTI and bundle url for the text/calendar mimetype,
NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType,
(CFStringRef)@"text/calendar",
NULL);
CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);
I see "com.apple.ical.ics" as the UTI and ".../MobileCoreTypes.bundle/" as the bundle URL. Not our app, but Apple. So I try putting com.apple.ical.ics into the LSItemContentTypes alongside my own, and into UTConformsTo in the export, but no go.
So basically, if Apple thinks they want to at some point handle some form of file type (that could be created 10 years after your app is live, mind you), you will have to change extension cause they'll simply not let you handle the file type.
Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4
I was having the same problem so I decided to download the source kit and install it according to how you posted above...
- Downloaded Source Kit
- Opened command prompt on that folder and typed python setup.py build
- Then I typed python setup.py install
It worked perfectly!
Now, some notes: when I typed python setup.py build
, I saw that Microsoft Visual Studio v9.0 C compiler was being used to build everything.
So probably it's something with your compiler not correctly configured or something...
Anyways, that worked with me so thank you!
How can I add (simple) tracing in C#?
I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String)
method where the TraceSource
object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt
. For the following code:
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
I successfully managed to log with the following diagnostics configuration:
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
fail to change placeholder color with Bootstrap 3
Assign the placeholder to a class selector like this:
.form-control::-webkit-input-placeholder { color: white; } /* WebKit, Blink, Edge */
.form-control:-moz-placeholder { color: white; } /* Mozilla Firefox 4 to 18 */
.form-control::-moz-placeholder { color: white; } /* Mozilla Firefox 19+ */
.form-control:-ms-input-placeholder { color: white; } /* Internet Explorer 10-11 */
.form-control::-ms-input-placeholder { color: white; } /* Microsoft Edge */
It will work then since a stronger selector was probably overriding your global. I'm on a tablet so i cant inspect and confirm which stronger selector it was :) But it does work I tried it in your fiddle.
This also answers your second question. By assigning it to a class or id and giving an input only that class you can control what inputs to style.
Getting raw SQL query string from PDO prepared statements
Mike's answer is working good until you are using the "re-use" bind value.
For example:
SELECT * FROM `an_modules` AS `m` LEFT JOIN `an_module_sites` AS `ms` ON m.module_id = ms.module_id WHERE 1 AND `module_enable` = :module_enable AND `site_id` = :site_id AND (`module_system_name` LIKE :search OR `module_version` LIKE :search)
The Mike's answer can only replace first :search but not the second.
So, I rewrite his answer to work with multiple parameters that can re-used properly.
public function interpolateQuery($query, $params) {
$keys = array();
$values = $params;
$values_limit = [];
$words_repeated = array_count_values(str_word_count($query, 1, ':_'));
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:'.$key.'/';
$values_limit[$key] = (isset($words_repeated[':'.$key]) ? intval($words_repeated[':'.$key]) : 1);
} else {
$keys[] = '/[?]/';
$values_limit = [];
}
if (is_string($value))
$values[$key] = "'" . $value . "'";
if (is_array($value))
$values[$key] = "'" . implode("','", $value) . "'";
if (is_null($value))
$values[$key] = 'NULL';
}
if (is_array($values)) {
foreach ($values as $key => $val) {
if (isset($values_limit[$key])) {
$query = preg_replace(['/:'.$key.'/'], [$val], $query, $values_limit[$key], $count);
} else {
$query = preg_replace(['/:'.$key.'/'], [$val], $query, 1, $count);
}
}
unset($key, $val);
} else {
$query = preg_replace($keys, $values, $query, 1, $count);
}
unset($keys, $values, $values_limit, $words_repeated);
return $query;
}
How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'
For you Laravel Mix users out there running Bootstrap4, you will need to run
npm installer tether --save
Then update you resources/assets/js/bootstrap.js
to load Tether and bring it to the window object.
Here is what mine looks like: (Note I also had to run npm install popper.js --save
)
window.$ = window.jQuery = require('jquery');
window.Popper = require('popper.js').default;
window.Tether = require('tether');
require('bootstrap');
Does List<T> guarantee insertion order?
The List<>
class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.
According to MSDN:
...List "Represents a strongly typed list of objects that can be
accessed by index."
The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.
You might be getting odd results from your code if you're moving the item later in the list, as your Remove()
will move all of the other items down one place before the call to Insert()
.
Can you boil your code down to something small enough to post?
Elasticsearch query to return all records
elasticsearch(ES) supports both a GET or a POST request for getting the data from the ES cluster index.
When we do a GET:
http://localhost:9200/[your index name]/_search?size=[no of records you want]&q=*:*
When we do a POST:
http://localhost:9200/[your_index_name]/_search
{
"size": [your value] //default 10
"from": [your start index] //default 0
"query":
{
"match_all": {}
}
}
I would suggest to use a UI plugin with elasticsearch http://mobz.github.io/elasticsearch-head/
This will help you get a better feeling of the indices you create and also test your indices.
JQuery - Storing ajax response into global variable
Similar to previous answer:
<script type="text/javascript">
var wait = false;
$(function(){
console.log('Loaded...');
loadPost(5);
});
$(window).scroll(function(){
if($(window).scrollTop() >= $(document).height() - $(window).height()-100){
// Get last item
var last = $('.post_id:last-of-type').val();
loadPost(1,last);
}
});
function loadPost(qty,offset){
if(wait !== true){
wait = true;
var data = {
items:qty,
oset:offset
}
$.ajax({
url:"api.php",
type:"POST",
dataType:"json",
data:data,
success:function(data){
//var d = JSON.parse(data);
console.log(data);
$.each(data.content, function(index, value){
$('#content').append('<input class="post_id" type="hidden" value="'+value.id+'">')
$('#content').append('<h2>'+value.id+'</h2>');
$('#content').append(value.content+'<hr>');
$('#content').append('<h3>'+value.date+'</h3>');
});
wait = false;
}
});
}
}
</script>
Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51
Here is what worked for me. I am using looped-back node module with Electron Js and faced this issue. After trying many things following worked for me.
In your package.json file in the scripts add following lines:
...
"scripts": {
"start": "electron .",
"rebuild": "electron-rebuild"
},
...
And then run following command npm run rebuild
Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?
What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles
By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.
You should try changing the value of -Xmx
and -Xms
.
How to make a .jar out from an Android Studio project
In the Android Studio IDE, access the "Run Anything bar" by:
CTRL+CTRL +gradle CreateFullJarRelease
+ENTER
After that you'll find your artefact in this folder in your project
Build > Intermediates > Full_jar > Release > CreateFullJarRelease > full.jar
OR
Gradle has already a Task
for that, in the gradle side-menu, under the other
folder.
Then scroll down to createFullJarRelease
and click it.
After that you'll find your artefact in this folder in your project
Build > Intermediates > Full_jar > Release > CreateFullJarRelease > full.jar
VBA Convert String to Date
Try using Replace
to see if it will work for you. The problem as I see it which has been mentioned a few times above is the CDate function is choking on the periods. You can use replace to change them to slashes. To answer your question about a Function in vba that can parse any date format, there is not any you have very limited options.
Dim current as Date, highest as Date, result() as Date
For Each itemDate in DeliveryDateArray
Dim tempDate As String
itemDate = IIf(Trim(itemDate) = "", "0", itemDate) 'Added per OP's request.
tempDate = Replace(itemDate, ".", "/")
current = Format(CDate(tempDate),"dd/mm/yyyy")
if current > highest then
highest = current
end if
' some more operations an put dates into result array
Next itemDate
'After activating final sheet...
Range("A1").Resize(UBound(result), 1).Value = Application.Transpose(result)
How to set a selected option of a dropdown list control using angular JS
I hope I understand your question, but the ng-model
directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant
. This means that changing item.selectedVariant
in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant
has a value of 0
, that item should get selected.
If variants
is an array of objects, item.selectedVariant
must be set to one of those objects. I do not know which information you have in your scope, but here's an example:
JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
This would leave the "b" item to be selected.
scp from Linux to Windows
I know this is old but I was struggling with the same. I haven't found a way to change directories, but if you just want to work with the C drive, scp defaults to C. To scp from Ubuntu to Windows, I ended up having to use (notice the double back-slashes):
scp /local/file/path [email protected]:Users\\Anshul\\Desktop
Hope this helps someone.
SQL Server String Concatenation with Null
From SQL Server 2012 this is all much easier with the CONCAT
function.
It treats NULL
as empty string
DECLARE @Column1 VARCHAR(50) = 'Foo',
@Column2 VARCHAR(50) = NULL,
@Column3 VARCHAR(50) = 'Bar';
SELECT CONCAT(@Column1,@Column2,@Column3); /*Returns FooBar*/
Deserializing JSON array into strongly typed .NET object
Afer looking at the source, for WP7 Hammock doesn't actually use Json.Net for JSON parsing. Instead it uses it's own parser which doesn't cope with custom types very well.
If using Json.Net directly it is possible to deserialize to a strongly typed collection inside a wrapper object.
var response = @"
{
""data"": [
{
""name"": ""A Jones"",
""id"": ""500015763""
},
{
""name"": ""B Smith"",
""id"": ""504986213""
},
{
""name"": ""C Brown"",
""id"": ""509034361""
}
]
}
";
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass));
return des.data.Count.ToString();
and with:
public class MyClass
{
public List<User> data { get; set; }
}
public class User
{
public string name { get; set; }
public string id { get; set; }
}
Having to create the extra object with the data property is annoying but that's a consequence of the way the JSON formatted object is constructed.
Documentation: Serializing and Deserializing JSON
What is the difference between ArrayList.clear() and ArrayList.removeAll()?
The source code for clear()
:
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
The source code for removeAll()
(As defined in AbstractCollection
):
public boolean removeAll(Collection<?> c) {
boolean modified = false;
Iterator<?> e = iterator();
while (e.hasNext()) {
if (c.contains(e.next())) {
e.remove();
modified = true;
}
}
return modified;
}
clear()
is much faster since it doesn't have to deal with all those extra method calls.
And as Atrey points out, c.contains(..)
increases the time complexity of removeAll
to O(n2) as opposed to clear
's O(n).
Android - Handle "Enter" in an EditText
This works fine on LG Android phones. It prevents ENTER
and other special characters to be interpreted as normal character. Next
or Done
button appears automatically and ENTER
works as expected.
edit.setInputType(InputType.TYPE_CLASS_TEXT);
How to upload files on server folder using jsp
Below code is working on my live server as well as in my own Lapy.
Note:
Please Create data folder in WebContent and put in any single image or any file(jsp or html file).
Add jar files
commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
commons-logging-1.0.4.jar
upload.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
UploadServlet.java
package com.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String DATA_DIRECTORY = "data";
private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
private static final int MAX_REQUEST_SIZE = 1024 * 1024;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);
// Sets the directory used to temporarily store files that are larger
// than the configured size threshold. We use temporary directory for
// java
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("")
+ File.separator + DATA_DIRECTORY;
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println(filePath);
// saves the file to upload directory
item.write(uploadedFile);
}
}
// displays done.jsp page after upload finished
getServletContext().getRequestDispatcher("/done.jsp").forward(
request, response);
} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
web.xml
<servlet>
<description></description>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
done.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>
How to Scroll Down - JQuery
$('.btnMedio').click(function(event) {
// Preventing default action of the event
event.preventDefault();
// Getting the height of the document
var n = $(document).height();
$('html, body').animate({ scrollTop: n }, 50);
// | |
// | --- duration (milliseconds)
// ---- distance from the top
});
nil detection in Go
You can also check like struct_var == (struct{})
. This does not allow you to compare to nil but it does check if it is initialized or not. Be careful while using this method. If your struct can have zero values for all of its fields you won't have great time.
package main
import "fmt"
type A struct {
Name string
}
func main() {
a := A{"Hello"}
var b A
if a == (A{}) {
fmt.Println("A is empty") // Does not print
}
if b == (A{}) {
fmt.Println("B is empty") // Prints
}
}
http://play.golang.org/p/RXcE06chxE
Issue with Task Scheduler launching a task
I solved the issue by opening up the properties on the exe-file itself. On the tab Compatibility there's a check box for privilege level that says "Run this as an administrator"
Even though my account have administration privileges it didn't work when I started it from task scheduler.
I unchecked the box and started it from the scheduler again and it worked.
Laravel PHP Command Not Found
If you are coming here 2021 this has worked for me also using Ubuntu 16.04
nano ~/.bash_profile
export PATH=$HOME/.config/composer/vendor/bin:$PATH
ctrl+x and save
source ~/.bash_profile
react-router getting this.props.location in child components
(Update) V5.1 & Hooks (Requires React >= 16.8)
You can use useHistory
, useLocation
and useRouteMatch
in your component to get match
, history
and location
.
const Child = () => {
const location = useLocation();
const history = useHistory();
const match = useRouteMatch("write-the-url-you-want-to-match-here");
return (
<div>{location.pathname}</div>
)
}
export default Child
(Update) V4 & V5
You can use withRouter
HOC in order to inject match
, history
and location
in your component props.
class Child extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
(Update) V3
You can use withRouter
HOC in order to inject router
, params
, location
, routes
in your component props.
class Child extends React.Component {
render() {
const { router, params, location, routes } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
Original answer
If you don't want to use the props, you can use the context as described in React Router documentation
First, you have to set up your childContextTypes
and getChildContext
class App extends React.Component{
getChildContext() {
return {
location: this.props.location
}
}
render() {
return <Child/>;
}
}
App.childContextTypes = {
location: React.PropTypes.object
}
Then, you will be able to access to the location object in your child components using the context like this
class Child extends React.Component{
render() {
return (
<div>{this.context.location.pathname}</div>
)
}
}
Child.contextTypes = {
location: React.PropTypes.object
}
How many bytes is unsigned long long?
Executive summary: it's 64 bits, or larger.
unsigned long long
is the same as unsigned long long int
. Its size is platform-dependent, but guaranteed by the C standard (ISO C99) to be at least 64 bits. There was no long long
in C89, but apparently even MSVC supports it, so it's quite portable.
In the current C++ standard (issued in 2003), there is no long long
, though many compilers support it as an extension. The upcoming C++0x standard will support it and its size will be the same as in C, so at least 64 bits.
You can get the exact size, in bytes (8 bits on typical platforms) with the expression sizeof(unsigned long long)
. If you want exactly 64 bits, use uint64_t
, which is defined in the header <stdint.h>
along with a bunch of related types (available in C99, C++11 and some current C++ compilers).
How to concatenate a std::string and an int?
You can concatenate int to string by using the given below simple trick, but note that this only works when integer is of single digit. Otherwise, add integer digit by digit to that string.
string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;
Output: John5
How to run C program on Mac OS X using Terminal?
Answer is chmod 755 hello - it makes file executable... It is funny, so no-one answered it. I had same problem on MacOS, which is now solved.
nano hello.c
make hello
chmod 755 hello
Then you run it by ./hello
clang --version
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin15.6.0
nothing was installed, nano make (clang) chmod - all inside MacOS already
What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?
The regex you're looking for is ^[A-Za-z.\s_-]+$
^
asserts that the regular expression must match at the beginning of the subject
[]
is a character class - any character that matches inside this expression is allowed
A-Z
allows a range of uppercase characters
a-z
allows a range of lowercase characters
.
matches a period
rather than a range of characters
\s
matches whitespace (spaces and tabs)
_
matches an underscore
-
matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-
) instead and put it anywhere in the character class, but that's less clear
+
asserts that the preceding expression (in our case, the character class) must match one or more times
$
Finally, this asserts that we're now at the end of the subject
When you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.
What is stability in sorting algorithms and why is it important?
It depends on what you do.
Imagine you've got some people records with a first and a last name field. First you sort the list by first name. If you then sort the list with a stable algorithm by last name, you'll have a list sorted by first name AND last name.
New lines inside paragraph in README.md
You can use a backslash at the end of a line.
So this:
a\
b\
c
will then look like:
a
b
c
Notice that there is no backslash at the end of the last line (after the 'c' character).
How to write a basic swap function in Java
//here is also another answer:
class SwapDemo{
static int a=1, b=2 ;
public static void main(String [] args){
Swap swp = new Swap();
swp.swaps(x,y);
System.out.println( " a (was 1)now is " + a + " b (was 2) now is " + b);
}
}
class Swap{
void swaps(int c, int d){
SwapDemo f = new SwapDemo();
f.a = c;
f.a = d;
}
}
MySQL LIKE IN()?
You can get desired result with help of Regular Expressions.
SELECT fiberbox from fiberbox where fiberbox REGEXP '[1740|1938|1940]';
We can test the above query please click SQL fiddle
SELECT fiberbox from fiberbox where fiberbox REGEXP '[174019381940]';
We can test the above query please click SQL fiddle
javascript - replace dash (hyphen) with a space
Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.
var str = "This-is---a--news-----item----";
Then to replace all dashes with single spaces, you could do this:
var newStr = str.split('-').filter(function(item) {
item = item ? item.replace(/-/g, ''): item
return item;
}).join(' ');
Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:
item = item ? item.replace(/-/g, ''): item
The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.
Then when your string join runs on the filtered elements, you end up with this output:
"This is a news item"
Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.
Regarding C++ Include another class
you need to forward declare the name of the class if you don't want a header:
class ClassTwo;
Important: This only works in some cases, see Als's answer for more information..
Setting cursor at the end of any text of a textbox
For Windows Forms you can control cursor position (and selection) with txtbox.SelectionStart
and txtbox.SelectionLength
properties. If you want to set caret to end try this:
txtbox.SelectionStart = txtbox.Text.Length;
txtbox.SelectionLength = 0;
For WPF see this question.
Compiling a C++ program with gcc
The difference between gcc and g++ are:
gcc | g++
compiles c source | compiles c++ source
use g++ instead of gcc to compile you c++ source.
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The reason for the exception is that and
implicitly calls bool
. First on the left operand and (if the left operand is True
) then on the right operand. So x and y
is equivalent to bool(x) and bool(y)
.
However the bool
on a numpy.ndarray
(if it contains more than one element) will throw the exception you have seen:
>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The bool()
call is implicit in and
, but also in if
, while
, or
, so any of the following examples will also fail:
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
There are more functions and statements in Python that hide bool
calls, for example 2 < x < 10
is just another way of writing 2 < x and x < 10
. And the and
will call bool
: bool(2 < x) and bool(x < 10)
.
The element-wise equivalent for and
would be the np.logical_and
function, similarly you could use np.logical_or
as equivalent for or
.
For boolean arrays - and comparisons like <
, <=
, ==
, !=
, >=
and >
on NumPy arrays return boolean NumPy arrays - you can also use the element-wise bitwise functions (and operators): np.bitwise_and
(&
operator)
>>> np.logical_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> np.bitwise_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> (arr > 1) & (arr < 3)
array([False, True, False], dtype=bool)
and bitwise_or
(|
operator):
>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> (arr <= 1) | (arr >= 3)
array([ True, False, True], dtype=bool)
A complete list of logical and binary functions can be found in the NumPy documentation:
How to create a Rectangle object in Java using g.fillRect method
Try this:
public void paint (Graphics g) {
Rectangle r = new Rectangle(xPos,yPos,width,height);
g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}
[edit]
// With explicit casting
public void paint (Graphics g) {
Rectangle r = new Rectangle(xPos, yPos, width, height);
g.fillRect(
(int)r.getX(),
(int)r.getY(),
(int)r.getWidth(),
(int)r.getHeight()
);
}
ASP.NET Web API application gives 404 when deployed at IIS 7
You may need to install Hotfix KB980368.
This article describes a update that enables certain Internet Information Services (IIS) 7.0 or IIS 7.5 handlers to handle requests whose URLs do not end with a period. Specifically, these handlers are mapped to "." request paths. Currently, a handler that is mapped to a "." request path handles only requests whose URLs end with a period. For example, the handler handles only requests whose URLs resemble the following URL:
http://www.example.com/ExampleSite/ExampleFile.
After you apply this update, handlers that are mapped to a "*." request path can handle requests whose URLs end with a period and requests whose URLs do not end with a period. For example, the handler can now handle requests that resemble the following URLs:
http://www.example.com/ExampleSite/ExampleFile
http://www.example.com/ExampleSite/ExampleFile.
After this patch is applied, ASP.NET 4 applications can handle requests for extensionless URLs. Therefore, managed HttpModules that run prior to handler execution will run. In some cases, the HttpModules can return errors for extensionless URLs. For example, an HttpModule that was written to expect only .aspx requests may now return errors when it tries to access the HttpContext.Session property.
SVN: Is there a way to mark a file as "do not commit"?
Guys I just found a solution. Given that TortoiseSVN works the way we want, I tried to install it under Linux - which means, running on Wine. Surprisingly it works! All you have to do is:
- Add files you want to skip commit by running: "svn changelist 'ignore-on-commit' ".
- Use TortoiseSVN to commit: "~/.wine/drive_c/Program\ Files/TortoiseSVN/bin/TortoiseProc.exe /command:commit /path:'
- The files excluded will be unchecked for commit by default, while other modified files will be checked. This is exactly the same as under Windows. Enjoy!
(The reason why need to exclude files by CLI is because the menu entry for doing that was not found, not sure why. Any way, this works great!)
How to convert URL parameters to a JavaScript object?
I needed to also deal with +
in the query part of the URL (decodeURIComponent doesn't), so I adapted Wolfgang's code to become:
var search = location.search.substring(1);
search = search?JSON.parse('{"' + search.replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
function(key, value) { return key===""?value:decodeURIComponent(value)}):{};
In my case, I'm using jQuery to get URL-ready form parameters, then this trick to build an object out of it and I can then easily update parameters on the object and rebuild the query URL, e.g.:
var objForm = JSON.parse('{"' + $myForm.serialize().replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
function(key, value) { return key===""?value:decodeURIComponent(value)});
objForm.anyParam += stringToAddToTheParam;
var serializedForm = $.param(objForm);
text-overflow: ellipsis not working
Add the Following lines in CSS for ellipsis to work
p {
display: block; // change it as per your requirement
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Error: expected type-specifier before 'ClassName'
For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).
This can be caused in many ways:
- You forgot to
#include
the header that defines it.
- Your inclusion guards (
#ifndef BLAH_H
) are defective (your #ifndef BLAH_H
doesn't match your #define BALH_H
due to a typo or copy+paste mistake).
- Your inclusion guards are accidentally used twice (two separate files both using
#define MYHEADER_H
, even if they are in separate directories)
- You forgot that you are using a template (eg.
new Vector()
should be new Vector<int>()
)
- The compiler is thinking you meant one scope when really you meant another (For example, if you have
NamespaceA::NamespaceB
, AND a <global scope>::NamespaceB
, if you are already within NamespaceA
, it'll look in NamespaceA::NamespaceB
and not bother checking <global scope>::NamespaceB
) unless you explicitly access it.
- You have a name clash (two entities with the same name, such as a class and an enum member).
To explicitly access something in the global namespace, prefix it with ::
, as if the global namespace is a namespace with no name (e.g. ::MyType
or ::MyNamespace::MyType
).
How to get row count using ResultSet in Java?
Most drivers support forward only resultset - so method like last, beforeFirst etc are not supported.
The first approach is suitable if you are also getting the data in the same loop - otherwise the resultSet has already been iterated and can not be used again.
In most cases the requirement is to get the number of rows a query would return without fetching the rows. Iterating through the result set to find the row count is almost same as processing the data. It is better to do another count(*) query instead.
C# Base64 String to JPEG Image
Front :
<Image Name="camImage"/>
Back:
public async void Base64ToImage(string base64String)
{
// read stream
var bytes = Convert.FromBase64String(base64String);
var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();
// decode image
var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);
// create bitmap
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
camImage.Source = output;
}
Create a CSS rule / class with jQuery at runtime
if you don' t want to assign a display:none to a css class, the right approach in to append to style, jQuery.Rule do the job.
I some cases you want to apply stiles before the append event of ajax content and fade content after append and this is it!
Unzip All Files In A Directory
This is a variant of Pedro Lobito answer using How to loop through a directory recursively to delete files with certain extensions teachings:
shopt -s globstar
root_directory="."
for zip_file_name in **/*.{zip,sublime\-package}; do
directory_name=`echo $zip_file_name | sed 's/\.\(zip\|sublime\-package\)$//'`
printf "Unpacking zip file \`$root_directory/$zip_file_name\`...\n"
if [ -f "$root_directory/$zip_file_name" ]; then
mkdir -p "$root_directory/$directory_name"
unzip -o -q "$root_directory/$zip_file_name" -d "$directory_name"
# Some files have the executable flag and were not being deleted because of it.
# chmod -x "$root_directory/$zip_file_name"
# rm -f "$root_directory/$zip_file_name"
fi
done
The remote server returned an error: (403) Forbidden
Add the following line:
request.UseDefaultCredentials = true;
This will let the application use the credentials of the logged in user to access the site. If it's returning 403, clearly it's expecting authentication.
It's also possible that you (now?) have an authenticating proxy in between you and the remote site. In which case, try:
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
Hope this helps.
How to connect to MySQL Database?
Looking at the code below, I tried it and found:
Instead of writing DBCon = DBConnection.Instance();
you should put DBConnection DBCon - new DBConnection();
(That worked for me)
and instead of MySqlComman cmd = new MySqlComman(query, DBCon.GetConnection());
you should put MySqlCommand cmd = new MySqlCommand(query, DBCon.GetConnection());
(it's missing the d)
Datatype for storing ip address in SQL Server
You can use varchar. The length of IPv4 is static, but that of IPv6 may be highly variable.
Unless you have a good reason to store it as binary, stick with a string (textual) type.
CodeIgniter Active Record - Get number of returned rows
This code segment for your Model
function getCount($tblName){
$query = $this->db->get($tblName);
$rowCount = $query->num_rows();
return $rowCount;
}
This is for controlr
public function index() {
$data['employeeCount']= $this->CMS_model->getCount("employee");
$this->load->view("hrdept/main",$data);
}
This is for view
<div class="count">
<?php echo $employeeCount; ?>
</div>
This code is used in my project and is working properly.
How to scroll to bottom in react?
I could not get any of below answers to work but simple js did the trick for me:
window.scrollTo({
top: document.body.scrollHeight,
left: 0,
behavior: 'smooth'
});
Exiting out of a FOR loop in a batch file?
You could simply use echo on
and you will see that goto :eof
or even exit /b
doesn't work as expected.
The code inside of the loop isn't executed anymore, but the loop is expanded for all numbers to the end.
That's why it's so slow.
The only way to exit a FOR /L loop seems to be the variant of exit
like the exsample of Wimmel, but this isn't very fast nor useful to access any results from the loop.
This shows 10 expansions, but none of them will be executed
echo on
for /l %%n in (1,1,10) do (
goto :eof
echo %%n
)
Foreach with JSONArray and JSONObject
Make sure you are using this org.json:
https://mvnrepository.com/artifact/org.json/json
if you are using Java 8 then you can use
import org.json.JSONArray;
import org.json.JSONObject;
JSONArray array = ...;
array.forEach(item -> {
JSONObject obj = (JSONObject) item;
parse(obj);
});
Just added a simple test to prove that it works:
Add the following dependency into your pom.xml
file (To prove that it works, I have used the old jar which was there when I have posted this answer)
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
And the simple test code snippet will be:
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String args[]) {
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
object.put("key1", "value1");
array.put(object);
array.forEach(item -> {
System.out.println(item.toString());
});
}
}
output:
{"key1":"value1"}
Open existing file, append a single line
The technically best way is probably this here:
private static async Task AppendLineToFileAsync([NotNull] string path, string line)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentOutOfRangeException(nameof(path), path, "Was null or whitepsace.");
if (!File.Exists(path))
throw new FileNotFoundException("File not found.", nameof(path));
using (var file = File.Open(path, FileMode.Append, FileAccess.Write))
using (var writer = new StreamWriter(file))
{
await writer.WriteLineAsync(line);
await writer.FlushAsync();
}
}
Iterating over Numpy matrix rows to apply a function each?
Use numpy.apply_along_axis()
. Assuming your matrix is 2D, you can use like:
import numpy as np
mymatrix = np.matrix([[11,12,13],
[21,22,23],
[31,32,33]])
def myfunction( x ):
return sum(x)
print np.apply_along_axis( myfunction, axis=1, arr=mymatrix )
#[36 66 96]
Can't create project on Netbeans 8.2
As the other people said, NetBeans is always going to use the latest version of JDK installed (currently JDK9) which is not working with NetBeans 8.2 and is causing problems as you guys mentioned.
You can solve this problem by forcing NetBeans to use JDK8 instead of deleting JDK9!
You just have to edit netbeans.conf
file:
MacOS /Applications/NetBeans/NetBeans8.2.app/Contents/Resources/NetBeans/etc
Windows C:\Program Files\NetBeans 8.2\etc\
Open netbeans.conf with your favourite editor and find this line: netbeans_jdkhome="/path/to/jdk"
Remove # sign in front of it and modify it by typing your desired JDK version (JDK8) home location.
Im not sure why is JDK9 not working with NetBeans8.2, but if I found out I will write it here...
Default JDK locations:
Mac OS ?
/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home
Windows ?
C:\Program Files\Java\jdk1.8.0_152
I've used jdk1.8.0_152 as example
Comparing Class Types in Java
As said earlier, your code will work unless you have the same classes loaded on two different class loaders.
This might happen in case you need multiple versions of the same class in memory at the same time, or you are doing some weird on the fly compilation stuff (as I am).
In this case, if you want to consider these as the same class (which might be reasonable depending on the case), you can match their names to compare them.
public static boolean areClassesQuiteTheSame(Class<?> c1, Class<?> c2) {
// TODO handle nulls maybe?
return c1.getCanonicalName().equals(c2.getCanonicalName());
}
Keep in mind that this comparison will do just what it does: compare class names; I don't think you will be able to cast from one version of a class to the other, and before looking into reflection, you might want to make sure there's a good reason for your classloader mess.
Server configuration by allow_url_fopen=0 in
Using relative instead of absolute file path solved the problem for me.
I had the same issue and setting allow_url_fopen=on
did not help. This means for instance :
use
$file="folder/file.ext";
instead of
$file="https://website.com/folder/file.ext";
in
$f=fopen($file,"r+");
"sed" command in bash
sed
is the Stream EDitor. It can do a whole pile of really cool things, but the most common is text replacement.
The s,%,$,g
part of the command line is the sed
command to execute. The s
stands for substitute, the ,
characters are delimiters (other characters can be used; /
, :
and @
are popular). The %
is the pattern to match (here a literal percent sign) and the $
is the second pattern to match (here a literal dollar sign). The g
at the end means to g
lobally replace on each line (otherwise it would only update the first match).
Android map v2 zoom to show all the markers
I worked the same problem for showing multiple markers in Kotlin using a fragment
first declare a list of markers
private lateinit var markers: MutableList<Marker>
initialize this in the oncreate method of the frament
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//initialize markers list
markers = mutableListOf()
return inflater.inflate(R.layout.fragment_driver_map, container, false)
}
on the OnMapReadyCallback add the markers to the markers list
private val callback = OnMapReadyCallback { googleMap ->
map = googleMap
markers.add(
map.addMarker(
MarkerOptions().position(riderLatLng)
.title("Driver")
.snippet("Driver")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))))
markers.add(
map.addMarker(
MarkerOptions().position(driverLatLng)
.title("Driver")
.snippet("Driver")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))))
Still on the callback
//create builder
val builder = LatLngBounds.builder()
//loop through the markers list
for (marker in markers) {
builder.include(marker.position)
}
//create a bound
val bounds = builder.build()
//set a 200 pixels padding from the edge of the screen
val cu = CameraUpdateFactory.newLatLngBounds(bounds,200)
//move and animate the camera
map.moveCamera(cu)
//animate camera by providing zoom and duration args, callBack set to null
map.animateCamera(CameraUpdateFactory.zoomTo(10f), 2000, null)
Merry coding guys
AndroidStudio: Failed to sync Install build tools
There may be some file access permission/restriction problems. First check to access the below directory manually, check whether your TARGET_VERSION exists, Then check the android sdk manager.
- sdk/build-tools/{TARGET_VERSION}
open() in Python does not create a file if it doesn't exist
The advantage of the following approach is that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally
, but much shorter.
with open("file.dat","a+") as f:
f.write(...)
...
a+ Opens a file for both appending and reading. The file pointer is
at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for
reading and writing. -Python file modes
seek() method sets the file's current position.
f.seek(pos [, (0|1|2)])
pos .. position of the r/w pointer
[] .. optionally
() .. one of ->
0 .. absolute position
1 .. relative position to current
2 .. relative position from end
Only "rwab+" characters are allowed; there must be exactly one of "rwa" - see Stack Overflow question Python file modes detail.
Android Gradle Could not reserve enough space for object heap
My fix using Android Studio 3.0.0 on Windows 10 is to remove entirely any jvm args from the gradle.properties file.
I am using the Android gradle wrapper 3.0.1 with gradle version 4.1. No gradlew commands were working, but a warning says that it's trying to ignore any jvm memory args as they were removed in 8 (which I assume is Java 8).
System.Net.WebException HTTP status code
Maybe something like this...
try
{
// ...
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
var response = ex.Response as HttpWebResponse;
if (response != null)
{
Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
}
else
{
// no http status code available
}
}
else
{
// no http status code available
}
}
Sorting table rows according to table header column using javascript or jquery
use Javascript sort() function
var $tbody = $('table tbody');
$tbody.find('tr').sort(function(a,b){
var tda = $(a).find('td:eq(1)').text(); // can replace 1 with the column you want to sort on
var tdb = $(b).find('td:eq(1)').text(); // this will sort on the second column
// if a < b return 1
return tda < tdb ? 1
// else if a > b return -1
: tda > tdb ? -1
// else they are equal - return 0
: 0;
}).appendTo($tbody);
If you want ascending you just have to reverse the > and <
Change the logic accordingly for you.
FIDDLE
Visual Studio move project to a different folder
- Close your solution in VS2012
- Move your project to the new location
- Open your solution
- Select the project that failed to load
- In the Properties tool window, there an editable “File path” entry that allows you to select the new project location
- Set the new path
- Right click on the project and click reload
Reading output of a command into an array in Bash
The other answers will break if output of command contains spaces (which is rather frequent) or glob characters like *
, ?
, [...]
.
To get the output of a command in an array, with one line per element, there are essentially 3 ways:
With Bash=4 use mapfile
—it's the most efficient:
mapfile -t my_array < <( my_command )
Otherwise, a loop reading the output (slower, but safe):
my_array=()
while IFS= read -r line; do
my_array+=( "$line" )
done < <( my_command )
As suggested by Charles Duffy in the comments (thanks!), the following might perform better than the loop method in number 2:
IFS=$'\n' read -r -d '' -a my_array < <( my_command && printf '\0' )
Please make sure you use exactly this form, i.e., make sure you have the following:
IFS=$'\n'
on the same line as the read
statement: this will only set the environment variable IFS
for the read
statement only. So it won't affect the rest of your script at all. The purpose of this variable is to tell read
to break the stream at the EOL character \n
.
-r
: this is important. It tells read
to not interpret the backslashes as escape sequences.
-d ''
: please note the space between the -d
option and its argument ''
. If you don't leave a space here, the ''
will never be seen, as it will disappear in the quote removal step when Bash parses the statement. This tells read
to stop reading at the nil byte. Some people write it as -d $'\0'
, but it is not really necessary. -d ''
is better.
-a my_array
tells read
to populate the array my_array
while reading the stream.
- You must use the
printf '\0'
statement after my_command
, so that read
returns 0
; it's actually not a big deal if you don't (you'll just get an return code 1
, which is okay if you don't use set -e
– which you shouldn't anyway), but just bear that in mind. It's cleaner and more semantically correct. Note that this is different from printf ''
, which doesn't output anything. printf '\0'
prints a null byte, needed by read
to happily stop reading there (remember the -d ''
option?).
If you can, i.e., if you're sure your code will run on Bash=4, use the first method. And you can see it's shorter too.
If you want to use read
, the loop (method 2) might have an advantage over method 3 if you want to do some processing as the lines are read: you have direct access to it (via the $line
variable in the example I gave), and you also have access to the lines already read (via the array ${my_array[@]}
in the example I gave).
Note that mapfile
provides a way to have a callback eval'd on each line read, and in fact you can even tell it to only call this callback every N lines read; have a look at help mapfile
and the options -C
and -c
therein. (My opinion about this is that it's a little bit clunky, but can be used sometimes if you only have simple things to do — I don't really understand why this was even implemented in the first place!).
Now I'm going to tell you why the following method:
my_array=( $( my_command) )
is broken when there are spaces:
$ # I'm using this command to test:
$ echo "one two"; echo "three four"
one two
three four
$ # Now I'm going to use the broken method:
$ my_array=( $( echo "one two"; echo "three four" ) )
$ declare -p my_array
declare -a my_array='([0]="one" [1]="two" [2]="three" [3]="four")'
$ # As you can see, the fields are not the lines
$
$ # Now look at the correct method:
$ mapfile -t my_array < <(echo "one two"; echo "three four")
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # Good!
Then some people will then recommend using IFS=$'\n'
to fix it:
$ IFS=$'\n'
$ my_array=( $(echo "one two"; echo "three four") )
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # It works!
But now let's use another command, with globs:
$ echo "* one two"; echo "[three four]"
* one two
[three four]
$ IFS=$'\n'
$ my_array=( $(echo "* one two"; echo "[three four]") )
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="t")'
$ # What?
That's because I have a file called t
in the current directory… and this filename is matched by the glob [three four]
… at this point some people would recommend using set -f
to disable globbing: but look at it: you have to change IFS
and use set -f
to be able to fix a broken technique (and you're not even fixing it really)! when doing that we're really fighting against the shell, not working with the shell.
$ mapfile -t my_array < <( echo "* one two"; echo "[three four]")
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="[three four]")'
here we're working with the shell!
python: how to identify if a variable is an array or a scalar
I am surprised that such a basic question doesn't seem to have an immediate answer in python.
It seems to me that nearly all proposed answers use some kind of type
checking, that is usually not advised in python and they seem restricted to a specific case (they fail with different numerical types or generic iteratable objects that are not tuples or lists).
For me, what works better is importing numpy and using array.size, for example:
>>> a=1
>>> np.array(a)
Out[1]: array(1)
>>> np.array(a).size
Out[2]: 1
>>> np.array([1,2]).size
Out[3]: 2
>>> np.array('125')
Out[4]: 1
Note also:
>>> len(np.array([1,2]))
Out[5]: 2
but:
>>> len(np.array(a))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-40-f5055b93f729> in <module>()
----> 1 len(np.array(a))
TypeError: len() of unsized object
How do I get the RootViewController from a pushed controller?
Swift version :
var rootViewController = self.navigationController?.viewControllers.first
ObjectiveC version :
UIViewController *rootViewController = [self.navigationController.viewControllers firstObject];
Where self is an instance of a UIViewController embedded in a UINavigationController.
Java: Multiple class declarations in one file
Yes you can, with public static members on an outer public class, like so:
public class Foo {
public static class FooChild extends Z {
String foo;
}
public static class ZeeChild extends Z {
}
}
and another file that references the above:
public class Bar {
public static void main(String[] args){
Foo.FooChild f = new Foo.FooChild();
System.out.println(f);
}
}
put them in the same folder. Compile with:
javac folder/*.java
and run with:
java -cp folder Bar
Could not open ServletContext resource
Are you having Tomcat unpack the WAR file? It seems that the files cannot be found on the classpath when a WAR file is loaded and it is not being unpacked.
Android EditText view Floating Hint in Material Design
You need to add the following to your module build.gradle file:
implementation 'com.google.android.material:material:1.0.0'
And use com.google.android.material.textfield.TextInputLayout in your XML:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/my_hint">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="UserName"/>
</com.google.android.material.textfield.TextInputLayout>
Copy rows from one Datatable to another DataTable?
As a result of the other posts, this is the shortest I could get:
DataTable destTable = sourceTable.Clone();
sourceTable.AsEnumerable().Where(row => /* condition */ ).ToList().ForEach(row => destTable.ImportRow(row));
How to set a time zone (or a Kind) of a DateTime value?
If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime()
to get the UTC time from your local time or myDateTime.ToLocalTime()
to convert the UTC time to the local machine's time.
// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();
// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();
If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime()
or TimeZoneInfo.ConvertTimeFromUtc()
.
// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);
// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);
List of available timezones
TimeZoneInfo class on MSDN
What is the strict aliasing rule?
Note
This is excerpted from my "What is the Strict Aliasing Rule and Why do we care?" write-up.
What is strict aliasing?
In C and C++ aliasing has to do with what expression types we are allowed to access stored values through. In both C and C++ the standard specifies which expression types are allowed to alias which types. The compiler and optimizer are allowed to assume we follow the aliasing rules strictly, hence the term strict aliasing rule. If we attempt to access a value using a type not allowed it is classified as undefined behavior(UB). Once we have undefined behavior all bets are off, the results of our program are no longer reliable.
Unfortunately with strict aliasing violations, we will often obtain the results we expect, leaving the possibility the a future version of a compiler with a new optimization will break code we thought was valid. This is undesirable and it is a worthwhile goal to understand the strict aliasing rules and how to avoid violating them.
To understand more about why we care, we will discuss issues that come up when violating strict aliasing rules, type punning since common techniques used in type punning often violate strict aliasing rules and how to type pun correctly.
Preliminary examples
Let's look at some examples, then we can talk about exactly what the standard(s) say, examine some further examples and then see how to avoid strict aliasing and catch violations we missed. Here is an example that should not be surprising (live example):
int x = 10;
int *ip = &x;
std::cout << *ip << "\n";
*ip = 12;
std::cout << x << "\n";
We have a int* pointing to memory occupied by an int and this is a valid aliasing. The optimizer must assume that assignments through ip could update the value occupied by x.
The next example shows aliasing that leads to undefined behavior (live example):
int foo( float *f, int *i ) {
*i = 1;
*f = 0.f;
return *i;
}
int main() {
int x = 0;
std::cout << x << "\n"; // Expect 0
x = foo(reinterpret_cast<float*>(&x), &x);
std::cout << x << "\n"; // Expect 0?
}
In the function foo we take an int* and a float*, in this example we call foo and set both parameters to point to the same memory location which in this example contains an int. Note, the reinterpret_cast is telling the compiler to treat the the expression as if it had the type specificed by its template parameter. In this case we are telling it to treat the expression &x as if it had type float*. We may naively expect the result of the second cout to be 0 but with optimization enabled using -O2 both gcc and clang produce the following result:
0
1
Which may not be expected but is perfectly valid since we have invoked undefined behavior. A float can not validly alias an int object. Therefore the optimizer can assume the constant 1 stored when dereferencing i will be the return value since a store through f could not validly affect an int object. Plugging the code in Compiler Explorer shows this is exactly what is happening(live example):
foo(float*, int*): # @foo(float*, int*)
mov dword ptr [rsi], 1
mov dword ptr [rdi], 0
mov eax, 1
ret
The optimizer using Type-Based Alias Analysis (TBAA) assumes 1 will be returned and directly moves the constant value into register eax which carries the return value. TBAA uses the languages rules about what types are allowed to alias to optimize loads and stores. In this case TBAA knows that a float can not alias and int and optimizes away the load of i.
Now, to the Rule-Book
What exactly does the standard say we are allowed and not allowed to do? The standard language is not straightforward, so for each item I will try to provide code examples that demonstrates the meaning.
What does the C11 standard say?
The C11 standard says the following in section 6.5 Expressions paragraph 7:
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:88)
— a type compatible with the effective type of the object,
int x = 1;
int *p = &x;
printf("%d\n", *p); // *p gives us an lvalue expression of type int which is compatible with int
— a qualified version of a type compatible with the effective type of the object,
int x = 1;
const int *p = &x;
printf("%d\n", *p); // *p gives us an lvalue expression of type const int which is compatible with int
— a type that is the signed or unsigned type corresponding to the effective type of the object,
int x = 1;
unsigned int *p = (unsigned int*)&x;
printf("%u\n", *p ); // *p gives us an lvalue expression of type unsigned int which corresponds to
// the effective type of the object
gcc/clang has an extension and also that allows assigning unsigned int* to int* even though they are not compatible types.
— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
int x = 1;
const unsigned int *p = (const unsigned int*)&x;
printf("%u\n", *p ); // *p gives us an lvalue expression of type const unsigned int which is a unsigned type
// that corresponds with to a qualified verison of the effective type of the object
— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
struct foo {
int x;
};
void foobar( struct foo *fp, int *ip ); // struct foo is an aggregate that includes int among its members so it can
// can alias with *ip
foo f;
foobar( &f, &f.x );
— a character type.
int x = 65;
char *p = (char *)&x;
printf("%c\n", *p ); // *p gives us an lvalue expression of type char which is a character type.
// The results are not portable due to endianness issues.
What the C++17 Draft Standard say
The C++17 draft standard in section [basic.lval] paragraph 11 says:
If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:63
(11.1) — the dynamic type of the object,
void *p = malloc( sizeof(int) ); // We have allocated storage but not started the lifetime of an object
int *ip = new (p) int{0}; // Placement new changes the dynamic type of the object to int
std::cout << *ip << "\n"; // *ip gives us a glvalue expression of type int which matches the dynamic type
// of the allocated object
(11.2) — a cv-qualified version of the dynamic type of the object,
int x = 1;
const int *cip = &x;
std::cout << *cip << "\n"; // *cip gives us a glvalue expression of type const int which is a cv-qualified
// version of the dynamic type of x
(11.3) — a type similar (as defined in 7.5) to the dynamic type of the object,
(11.4) — a type that is the signed or unsigned type corresponding to the dynamic type of the object,
// Both si and ui are signed or unsigned types corresponding to each others dynamic types
// We can see from this godbolt(https://godbolt.org/g/KowGXB) the optimizer assumes aliasing.
signed int foo( signed int &si, unsigned int &ui ) {
si = 1;
ui = 2;
return si;
}
(11.5) — a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
signed int foo( const signed int &si1, int &si2); // Hard to show this one assumes aliasing
(11.6) — an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
struct foo {
int x;
};
// Compiler Explorer example(https://godbolt.org/g/z2wJTC) shows aliasing assumption
int foobar( foo &fp, int &ip ) {
fp.x = 1;
ip = 2;
return fp.x;
}
foo f;
foobar( f, f.x );
(11.7) — a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
struct foo { int x ; };
struct bar : public foo {};
int foobar( foo &f, bar &b ) {
f.x = 1;
b.x = 2;
return f.x;
}
(11.8) — a char, unsigned char, or std::byte type.
int foo( std::byte &b, uint32_t &ui ) {
b = static_cast<std::byte>('a');
ui = 0xFFFFFFFF;
return std::to_integer<int>( b ); // b gives us a glvalue expression of type std::byte which can alias
// an object of type uint32_t
}
Worth noting signed char is not included in the list above, this is a notable difference from C which says a character type.
What is Type Punning
We have gotten to this point and we may be wondering, why would we want to alias for? The answer typically is to type pun, often the methods used violate strict aliasing rules.
Sometimes we want to circumvent the type system and interpret an object as a different type. This is called type punning, to reinterpret a segment of memory as another type. Type punning is useful for tasks that want access to the underlying representation of an object to view, transport or manipulate. Typical areas we find type punning being used are compilers, serialization, networking code, etc…
Traditionally this has been accomplished by taking the address of the object, casting it to a pointer of the type we want to reinterpret it as and then accessing the value, or in other words by aliasing. For example:
int x = 1 ;
// In C
float *fp = (float*)&x ; // Not a valid aliasing
// In C++
float *fp = reinterpret_cast<float*>(&x) ; // Not a valid aliasing
printf( "%f\n", *fp ) ;
As we have seen earlier this is not a valid aliasing, so we are invoking undefined behavior. But traditionally compilers did not take advantage of strict aliasing rules and this type of code usually just worked, developers have unfortunately gotten used to doing things this way. A common alternate method for type punning is through unions, which is valid in C but undefined behavior in C++ (see live example):
union u1
{
int n;
float f;
} ;
union u1 u;
u.f = 1.0f;
printf( "%d\n”, u.n ); // UB in C++ n is not the active member
This is not valid in C++ and some consider the purpose of unions to be solely for implementing variant types and feel using unions for type punning is an abuse.
How do we Type Pun correctly?
The standard method for type punning in both C and C++ is memcpy. This may seem a little heavy handed but the optimizer should recognize the use of memcpy for type punning and optimize it away and generate a register to register move. For example if we know int64_t is the same size as double:
static_assert( sizeof( double ) == sizeof( int64_t ) ); // C++17 does not require a message
we can use memcpy:
void func1( double d ) {
std::int64_t n;
std::memcpy(&n, &d, sizeof d);
//...
At a sufficient optimization level any decent modern compiler generates identical code to the previously mentioned reinterpret_cast method or union method for type punning. Examining the generated code we see it uses just register mov (live Compiler Explorer Example).
C++20 and bit_cast
In C++20 we may gain bit_cast (implementation available in link from proposal) which gives a simple and safe way to type-pun as well as being usable in a constexpr context.
The following is an example of how to use bit_cast to type pun a unsigned int to float, (see it live):
std::cout << bit_cast<float>(0x447a0000) << "\n" ; //assuming sizeof(float) == sizeof(unsigned int)
In the case where To and From types don't have the same size, it requires us to use an intermediate struct15. We will use a struct containing a sizeof( unsigned int ) character array (assumes 4 byte unsigned int) to be the From type and unsigned int as the To type.:
struct uint_chars {
unsigned char arr[sizeof( unsigned int )] = {} ; // Assume sizeof( unsigned int ) == 4
};
// Assume len is a multiple of 4
int bar( unsigned char *p, size_t len ) {
int result = 0;
for( size_t index = 0; index < len; index += sizeof(unsigned int) ) {
uint_chars f;
std::memcpy( f.arr, &p[index], sizeof(unsigned int));
unsigned int result = bit_cast<unsigned int>(f);
result += foo( result );
}
return result ;
}
It is unfortunate that we need this intermediate type but that is the current constraint of bit_cast.
Catching Strict Aliasing Violations
We don't have a lot of good tools for catching strict aliasing in C++, the tools we have will catch some cases of strict aliasing violations and some cases of misaligned loads and stores.
gcc using the flag -fstrict-aliasing and -Wstrict-aliasing can catch some cases although not without false positives/negatives. For example the following cases will generate a warning in gcc (see it live):
int a = 1;
short j;
float f = 1.f; // Originally not initialized but tis-kernel caught
// it was being accessed w/ an indeterminate value below
printf("%i\n", j = *(reinterpret_cast<short*>(&a)));
printf("%i\n", j = *(reinterpret_cast<int*>(&f)));
although it will not catch this additional case (see it live):
int *p;
p=&a;
printf("%i\n", j = *(reinterpret_cast<short*>(p)));
Although clang allows these flags it apparently does not actually implement the warnings.
Another tool we have available to us is ASan which can catch misaligned loads and stores. Although these are not directly strict aliasing violations they are a common result of strict aliasing violations. For example the following cases will generate runtime errors when built with clang using -fsanitize=address
int *x = new int[2]; // 8 bytes: [0,7].
int *u = (int*)((char*)x + 6); // regardless of alignment of x this will not be an aligned address
*u = 1; // Access to range [6-9]
printf( "%d\n", *u ); // Access to range [6-9]
The last tool I will recommend is C++ specific and not strictly a tool but a coding practice, don't allow C-style casts. Both gcc and clang will produce a diagnostic for C-style casts using -Wold-style-cast. This will force any undefined type puns to use reinterpret_cast, in general reinterpret_cast should be a flag for closer code review. It is also easier to search your code base for reinterpret_cast to perform an audit.
For C we have all the tools already covered and we also have tis-interpreter, a static analyzer that exhaustively analyzes a program for a large subset of the C language. Given a C verions of the earlier example where using -fstrict-aliasing misses one case (see it live)
int a = 1;
short j;
float f = 1.0 ;
printf("%i\n", j = *((short*)&a));
printf("%i\n", j = *((int*)&f));
int *p;
p=&a;
printf("%i\n", j = *((short*)p));
tis-interpeter is able to catch all three, the following example invokes tis-kernal as tis-interpreter (output is edited for brevity):
./bin/tis-kernel -sa example1.c
...
example1.c:9:[sa] warning: The pointer (short *)(& a) has type short *. It violates strict aliasing
rules by accessing a cell with effective type int.
...
example1.c:10:[sa] warning: The pointer (int *)(& f) has type int *. It violates strict aliasing rules by
accessing a cell with effective type float.
Callstack: main
...
example1.c:15:[sa] warning: The pointer (short *)p has type short *. It violates strict aliasing rules by
accessing a cell with effective type int.
Finally there is TySan which is currently in development. This sanitizer adds type checking information in a shadow memory segment and checks accesses to see if they violate aliasing rules. The tool potentially should be able to catch all aliasing violations but may have a large run-time overhead.
XSLT string replace
replace
isn't available for XSLT 1.0.
Codesling has a template for string-replace you can use as a substitute for the function:
<xsl:template name="string-replace-all">
<xsl:param name="text" />
<xsl:param name="replace" />
<xsl:param name="by" />
<xsl:choose>
<xsl:when test="$text = '' or $replace = ''or not($replace)" >
<!-- Prevent this routine from hanging -->
<xsl:value-of select="$text" />
</xsl:when>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text,$replace)" />
<xsl:value-of select="$by" />
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="substring-after($text,$replace)" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
invoked as:
<xsl:variable name="newtext">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="$text" />
<xsl:with-param name="replace" select="a" />
<xsl:with-param name="by" select="b" />
</xsl:call-template>
</xsl:variable>
On the other hand, if you literally only need to replace one character with another, you can call translate
which has a similar signature. Something like this should work fine:
<xsl:variable name="newtext" select="translate($text,'a','b')"/>
Also, note, in this example, I changed the variable name to "newtext", in XSLT variables are immutable, so you can't do the equivalent of $foo = $foo
like you had in your original code.
How to iterate over a JSONObject?
Iterator<JSONObject> iterator = jsonObject.values().iterator();
while (iterator.hasNext()) {
jsonChildObject = iterator.next();
// Do whatever you want with jsonChildObject
String id = (String) jsonChildObject.get("id");
}
Bootstrap Datepicker - Months and Years Only
I am using bootstrap calender for future date not allow with allow change in months & year only..
var j = jQuery.noConflict();
j(function () {
j(".datepicker").datepicker({ dateFormat: "dd-M-yy" }).val()
});
j(function () {
j(".Futuredatenotallowed").datepicker({
changeMonth: true,
maxDate: 0,
changeYear: true,
dateFormat: 'dd-M-yy',
language: "tr"
}).on('changeDate', function (ev) {
$(this).blur();
$(this).datepicker('hide');
}).val()
});
Regex for string not ending with given suffix
You don't give us the language, but if your regex flavour support look behind assertion, this is what you need:
.*(?<!a)$
(?<!a)
is a negated lookbehind assertion that ensures, that before the end of the string (or row with m
modifier), there is not the character "a".
See it here on Regexr
You can also easily extend this with other characters, since this checking for the string and isn't a character class.
.*(?<!ab)$
This would match anything that does not end with "ab", see it on Regexr
MySQL query to get column names?
This question is old, but I got here looking for a way to find a given query its field names in a dynamic way (not necessarily only the fields of a table). And since people keep pointing this as the answer for that given task in other related questions, I'm sharing the way I found it can be done, using Gavin Simpson's tips:
//Function to generate a HTML table from a SQL query
function myTable($obConn,$sql)
{
$rsResult = mysqli_query($obConn, $sql) or die(mysqli_error($obConn));
if(mysqli_num_rows($rsResult)>0)
{
//We start with header. >>>Here we retrieve the field names<<<
echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\"><tr align=\"center\" bgcolor=\"#CCCCCC\">";
$i = 0;
while ($i < mysqli_num_fields($rsResult)){
$field = mysqli_fetch_field_direct($rsResult, $i);
$fieldName=$field->name;
echo "<td><strong>$fieldName</strong></td>";
$i = $i + 1;
}
echo "</tr>";
//>>>Field names retrieved<<<
//We dump info
$bolWhite=true;
while ($row = mysqli_fetch_assoc($rsResult)) {
echo $bolWhite ? "<tr bgcolor=\"#CCCCCC\">" : "<tr bgcolor=\"#FFF\">";
$bolWhite=!$bolWhite;
foreach($row as $data) {
echo "<td>$data</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
This can be easily modded to insert the field names in an array.
Using a simple: $sql="SELECT * FROM myTable LIMIT 1"
can give you the fields of any table, without needing to use SHOW COLUMNS
or any extra php module, if needed (removing the data dump part).
Hopefully this helps someone else.
JavaScript onclick redirect
Doing this fixed my issue
<script type="text/javascript">
function SubmitFrm(){
var Searchtxt = document.getElementById("txtSearch").value;
window.location = "http://www.mysite.com/search/?Query=" + Searchtxt;
}
</script>
I changed .value();
to .value;
taking out the ()
I did not change anything in my text field or submit button
<input name="txtSearch" type="text" id="txtSearch" class="field" />
<input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" />
Works like a charm.
Does not contain a static 'main' method suitable for an entry point
For future readers who faced same issue with Windows Forms Application, one solution is to add these lines to your main/start up form class:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyMainForm());
}
Then go to project properties > Application > Startup Object dropdown, should see the namespace.MyMainForm, select it, clean and build the solution. And it should work.
List<T> or IList<T>
What if .NET 5.0 replaces System.Collections.Generic.List<T>
to System.Collection.Generics.LinearList<T>
. .NET always owns the name List<T>
but they guarantee that IList<T>
is a contract. So IMHO we (atleast I) are not supposed to use someone's name (though it is .NET in this case) and get into trouble later.
In case of using IList<T>
, the caller is always guareented things to work, and the implementer is free to change the underlying collection to any alternative concrete implementation of IList
Use of def, val, and var in scala
I'd start by the distinction that exists in Scala between def, val and var.
def - defines an immutable label for the right side content which is lazily evaluated - evaluate by name.
val - defines an immutable label for the right side content which is eagerly/immediately evaluated - evaluated by value.
var - defines a mutable variable, initially set to the evaluated right side content.
Example, def
scala> def something = 2 + 3 * 4
something: Int
scala> something // now it's evaluated, lazily upon usage
res30: Int = 14
Example, val
scala> val somethingelse = 2 + 3 * 5 // it's evaluated, eagerly upon definition
somethingelse: Int = 17
Example, var
scala> var aVariable = 2 * 3
aVariable: Int = 6
scala> aVariable = 5
aVariable: Int = 5
According to above, labels from def and val cannot be reassigned, and in case of any attempt an error like the below one will be raised:
scala> something = 5 * 6
<console>:8: error: value something_= is not a member of object $iw
something = 5 * 6
^
When the class is defined like:
scala> class Person(val name: String, var age: Int)
defined class Person
and then instantiated with:
scala> def personA = new Person("Tim", 25)
personA: Person
an immutable label is created for that specific instance of Person (i.e. 'personA'). Whenever the mutable field 'age' needs to be modified, such attempt fails:
scala> personA.age = 44
personA.age: Int = 25
as expected, 'age' is part of a non-mutable label. The correct way to work on this consists in using a mutable variable, like in the following example:
scala> var personB = new Person("Matt", 36)
personB: Person = Person@59cd11fe
scala> personB.age = 44
personB.age: Int = 44 // value re-assigned, as expected
as clear, from the mutable variable reference (i.e. 'personB') it is possible to modify the class mutable field 'age'.
I would still stress the fact that everything comes from the above stated difference, that has to be clear in mind of any Scala programmer.
Where are shared preferences stored?
Preferences can either be set in code or can be found in res/xml/preferences.xml. You can read more about preferences on the Android SDK website.
What is com.sun.proxy.$Proxy
Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler
, which defines a method that is invoked when a proxy method is invoked.
You create them by using the call
Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
The arguments are:
classLoader
. Once the class is generated, it is loaded with this class loader.
interfaces
. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.
invocationHandler
. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler
. When a method from any of the supported interfaces, or hashCode
, equals
, or toString
, is invoked, the method invoke
is invoked on the handler, passing the Method
object for the method to be invoked and the arguments passed.
For more on this, see the documentation for the Proxy
class.
Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.
Error:Cause: unable to find valid certification path to requested target
For me this worked:
buildscript {
repositories {
maven { url "http://jcenter.bintray.com"}
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
...
}
allprojects {
repositories {
mavenCentral()
jcenter{ url "http://jcenter.bintray.com/" }
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
}
Best way to increase heap size in catalina.bat file
If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents
export JAVA_OPTS="-server -Xmx512m"
For Windows you will need, in setenv.bat, something like
set JAVA_OPTS=-server -Xmx768m
Original answer here
After you run startup.bat
, you can easily confirm the correct settings have been applied provided you have turned @echo
on somewhere in your catatlina.bat
file (a good place could be immediately after echo Using CLASSPATH: "%CLASSPATH%"
):
Remove HTML tags from string including   in C#
I took @Ravi Thapliyal's code and made a method: It is simple and might not clean everything, but so far it is doing what I need it to do.
public static string ScrubHtml(string value) {
var step1 = Regex.Replace(value, @"<[^>]+>| ", "").Trim();
var step2 = Regex.Replace(step1, @"\s{2,}", " ");
return step2;
}
Batch command date and time in file name
As Vicky already pointed out, %DATE%
and %TIME%
return the current date and time using the short date and time formats that are fully (endlessly) customizable.
One user may configure its system to return Fri040811 08.03PM while another user may choose 08/04/2011 20:30.
It's a complete nightmare for a BAT programmer.
Changing the format to a firm format may fix the problem, provided you restore back the previous format before leaving the BAT file. But it may be subject to nasty race conditions and complicate recovery in cancelled BAT files.
Fortunately, there is an alternative.
You may use WMIC, instead. WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table
returns the date and time in a invariable way. Very convenient to directly parse it with a FOR /F
command.
So, putting the pieces together, try this as a starting point...
SETLOCAL enabledelayedexpansion
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
SET /A FD=%%F*1000000+%%D*100+%%A
SET /A FT=10000+%%B*100+%%C
SET FT=!FT:~-4!
ECHO Archive_!FD!_!FT!.zip
)
MySQL Calculate Percentage
try this
SELECT group_name, employees, surveys, COUNT( surveys ) AS test1,
concat(round(( surveys/employees * 100 ),2),'%') AS percentage
FROM a_test
GROUP BY employees
DEMO HERE
jQuery datepicker years shown
i think this may work as well
$(function () {
$(".DatepickerInputdob").datepicker({
dateFormat: "d M yy",
changeMonth: true,
changeYear: true,
yearRange: '1900:+0',
defaultDate: '01 JAN 1900'
});
Get value when selected ng-option changes
I have tried some solutions,but here is basic production snippet. Please, pay attention to console output during quality assurance of this snippet.
Mark Up :
<!DOCTYPE html>
<html ng-app="appUp">
<head>
<title>
Angular Select snippet
</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
</head>
<body ng-controller="upController">
<div class="container">
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-3">
<div class="form-group">
<select name="slct" id="slct" class="form-control" ng-model="selBrand" ng-change="Changer(selBrand)" ng-options="brand as brand.name for brand in stock">
<option value="">
Select Brand
</option>
</select>
</div>
<div class="form-group">
<input type="hidden" name="delimiter" value=":" ng-model="delimiter" />
<input type="hidden" name="currency" value="$" ng-model="currency" />
<span>
{{selBrand.name}}{{delimiter}}{{selBrand.price}}{{currency}}
</span>
</div>
</div>
<div class="col-md-4">
</div>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js">
</script>
<script src="js/ui-bootstrap-tpls-2.5.0.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Code:
var c = console;
var d = document;
var app = angular.module('appUp',[]).controller('upController',function($scope){
$scope.stock = [{
name:"Adidas",
price:420
},
{
name:"Nike",
price:327
},
{
name:"Clark",
price:725
}
];//data
$scope.Changer = function(){
if($scope.selBrand){
c.log("brand:"+$scope.selBrand.name+",price:"+$scope.selBrand.price);
$scope.currency = "$";
$scope.delimiter = ":";
}
else{
$scope.currency = "";
$scope.delimiter = "";
c.clear();
}
}; // onchange handler
});
Explanation:
important point here is null check of the changed value, i.e. if value is 'undefined' or 'null' we should to handle this situation.
Extracting a parameter from a URL in WordPress
You can try this function
/**
* Gets the request parameter.
*
* @param string $key The query parameter
* @param string $default The default value to return if not found
*
* @return string The request parameter.
*/
function get_request_parameter( $key, $default = '' ) {
// If not request set
if ( ! isset( $_REQUEST[ $key ] ) || empty( $_REQUEST[ $key ] ) ) {
return $default;
}
// Set so process it
return strip_tags( (string) wp_unslash( $_REQUEST[ $key ] ) );
}
Here is what is happening in the function
Here three things are happening.
- First we check if the request key is present or not. If not, then just return a default value.
- If it is set, then we first remove slashes by doing wp_unslash. Read here why it is better than stripslashes_deep.
- Then we sanitize the value by doing a simple strip_tags. If you expect rich text from parameter, then run it through wp_kses or similar functions.
All of this information plus more info on the thinking behind the function can be found on this link https://www.intechgrity.com/correct-way-get-url-parameter-values-wordpress/
Difference between EXISTS and IN in SQL?
The reason is that the EXISTS operator works based on the “at least found” principle. It returns true and stops scanning table once at least one matching row found.
On the other hands, when the IN operator is combined with a subquery, MySQL must process the subquery first, and then uses the result of the subquery to process the whole query.
The general rule of thumb is that if the subquery contains a large
volume of data, the EXISTS operator provides a better performance.
However, the query that uses the IN operator will perform faster if
the result set returned from the subquery is very small.
How does one get started with procedural generation?
There is an excellent book about the topic:
http://www.amazon.com/Texturing-Modeling-Third-Procedural-Approach/dp/1558608486
It is biased toward non-real-time visual effects and animation generation, but the theory and ideas are usable outside of these fields, I suppose.
It may also worth to mention that there is a professional software package that implements a complete procedural workflow called SideFX's Houdini. You can use it to invent and prototype procedural solutions to problems, that you can later translate to code.
While it's a rather expensive package, it has a free evaluation licence, which can be used as a very nice educational and/or engineering tool.
Checking if a variable is an integer in PHP
An integer starting with 0 will cause fatal error as of PHP 7, because it might interpret it as an octal character.
Invalid octal literals
Previously, octal literals that contained invalid numbers were
silently truncated (0128 was taken as 012). Now, an invalid octal
literal will cause a parse error.
So you might want to remove leading zeros from your integer, first:
$var = ltrim($var, 0);
How to change the href for a hyperlink using jQuery
Change the HREF of the Wordpress Avada Theme Logo Image
If you install the ShortCode Exec PHP plugin the you can create this Shortcode which I called myjavascript
?><script type="text/javascript">
jQuery(document).ready(function() {
jQuery("div.fusion-logo a").attr("href","tel:303-985-9850");
});
</script>
You can now go to Appearance/Widgets and pick one of the footer widget areas and use a text widget to add the following shortcode
[myjavascript]
The selector may change depending upon what image your using and if it's retina ready but you can always figure it out by using developers tools.
How to include scripts located inside the node_modules folder?
I didn't find any clean solutions (I don't want to expose the source of all my node_modules) so I just wrote a Powershell script to copy them:
$deps = "leaflet", "leaflet-search", "material-components-web"
foreach ($dep in $deps) {
Copy-Item "node_modules/$dep/dist" "static/$dep" -Recurse
}
Python: Find index of minimum item in list of floats
I think it's worth putting a few timings up here for some perspective.
All timings done on OS-X 10.5.8 with python2.7
John Clement's answer:
python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop
David Wolever's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop
OP's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop
Note that I'm purposefully putting the smallest item last in the list to make .index
as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.
Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).
Angular @ViewChild() error: Expected 2 arguments, but got 1
Angular 8
In Angular 8, ViewChild has another param
@ViewChild('nameInput', {static: false}) component : Component
You can read more about it here and here
Angular 9 & Angular 10
In Angular 9
default value is static: false
, so doesn't need to provide param unless you want to use {static: true}
Popup Message boxes
A couple of "enhancements" I use for debugging, especially when running projects (ie not in debug mode).
- Default the message-box title to the name of the calling method. This is handy for stopping a thread at a given point, but must be cleaned-up before release.
Automatically copy the caller-name and message to the clipboard, because you can't search an image!
package forumposts;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import javax.swing.JOptionPane;
public final class MsgBox
{
public static void info(String message) {
info(message, theNameOfTheMethodThatCalledMe());
}
public static void info(String message, String caller) {
show(message, caller, JOptionPane.INFORMATION_MESSAGE);
}
static void error(String message) {
error(message, theNameOfTheMethodThatCalledMe());
}
public static void error(String message, String caller) {
show(message, caller, JOptionPane.ERROR_MESSAGE);
}
public static void show(String message, String title, int iconId) {
setClipboard(title+":"+NEW_LINE+message);
JOptionPane.showMessageDialog(null, message, title, iconId);
}
private static final String NEW_LINE = System.lineSeparator();
public static String theNameOfTheMethodThatCalledMe() {
return Thread.currentThread().getStackTrace()[3].getMethodName();
}
public static void setClipboard(String message) {
CLIPBOARD.setContents(new StringSelection(message), null);
// nb: we don't respond to the "your content was splattered"
// event, so it's OK to pass a null owner.
}
private static final Toolkit AWT_TOOLKIT = Toolkit.getDefaultToolkit();
private static final Clipboard CLIPBOARD = AWT_TOOLKIT.getSystemClipboard();
}
The full class also has debug and warning methods, but I cut them for brevity and you get the main points anyway. You can use a public static boolean isDebugEnabled to suppress debug messages. If done properly the optimizer will (almost) remove these method calls from your production code. See: http://c2.com/cgi/wiki?ConditionalCompilationInJava
Cheers. Keith.
Finding common rows (intersection) in two Pandas dataframes
In SQL, this problem could be solved by several methods:
select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)
or join and then unpivot (possible in SQL server)
select
df1.user_id,
c.rating
from df1
inner join df2 on df2.user_i = df1.user_id
outer apply (
select df1.rating union all
select df2.rating
) as c
Second one could be written in pandas with something like:
>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
user_id rating
0 3 20
0 3 30
How do you create a Distinct query in HQL
If you need to use new keyword for a custom DTO in your select statement and need distinct elements, use new outside of new like as follows-
select distinct new com.org.AssetDTO(a.id, a.address, a.status) from Asset as a where ...
Add & delete view from Layout
you can use addView or removeView
java:
// Root Layout
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setGravity(Gravity.CENTER);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// TextView
TextView textView = new TextView(context);
textView.setText("Sample");
// Add TextView in LinearLayout
linearLayout.addView(textView);
// Remove TextView from LinearLayout
linearLayout.removeView(textView);
kotlin:
// Root Layout
val linearLayout = LinearLayout(context)
linearLayout.gravity = Gravity.CENTER
linearLayout.orientation = LinearLayout.VERTICAL
// TextView
val textView = TextView(context)
textView.text = "Sample"
// Add TextView in LinearLayout
linearLayout.addView(textView)
// Remove TextView from LinearLayout
linearLayout.removeView(textView)
Calculate distance in meters when you know longitude and latitude in java
Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)
public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
Deleting Row in SQLite in Android
But the Accepted answer Not worked for me. I think String should be In SQL, strings must be quoted. So, in my case this worked for me against the accepted answer :
database.delete(TABLE_DAILY_NOTES, WORK_ENTRY_CLUMN_NAME + "='" + workEntry+"'", null);
Sending arrays with Intent.putExtra
This code sends array of integer values
Initialize array List
List<Integer> test = new ArrayList<Integer>();
Add values to array List
test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);
Send the array list values to target activity
intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);
here you get values on targetActivty
Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");
Dynamically create and submit form
Josepmra example works well for what i need.
But i had to add the line
form.appendTo( document.body )
for it to work.
var form = $(document.createElement('form'));
$(form).attr("action", "reserves.php");
$(form).attr("method", "POST");
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "mydata")
.val("bla" );
$(form).append($(input));
form.appendTo( document.body )
$(form).submit();
The calling thread must be STA, because many UI components require this
If you make the call from the main thread, you must add the STAThread attribute to the Main method, as stated in the previous answer.
If you use a separate thread, it needs to be in a STA (single-threaded apartment), which is not the case for background worker threads. You have to create the thread yourself, like this:
Thread t = new Thread(ThreadProc);
t.SetApartmentState(ApartmentState.STA);
t.Start();
with ThreadProc being a delegate of type ThreadStart.
How to catch SQLServer timeout exceptions
Updated for c# 6:
try
{
// some code
}
catch (SqlException ex) when (ex.Number == -2) // -2 is a sql timeout
{
// handle timeout
}
Very simple and nice to look at!!
BeautifulSoup getText from between <p>, not picking up subsequent paragraphs
You are getting close!
# Find all of the text between paragraph tags and strip out the html
page = soup.find('p').getText()
Using find (as you've noticed) stops after finding one result. You need find_all if you want all the paragraphs. If the pages are formatted consistently ( just looked over one), you could also use something like
soup.find('div',{'id':'ctl00_PlaceHolderMain_RichHtmlField1__ControlWrapper_RichHtmlField'})
to zero in on the body of the article.
RecyclerView onClick
I have looked thorugh all of the anwers and was not quite satasifed. I found much easier and faster solution. Wanted to share for future readers.
- Choose any
View
inside your single recycler item.
- Get parent of this
View
(Make sure you cast to appropirate ViewGroup
)
- Set your
onClickListener
to this parent.
Sample code (It is written inside your onBindViewHolder
method of your adapter
):
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
ConstraintLayout parent = (ConstraintLayout) holder.title.getParent();
parent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "Clicked recycler view item at position " + position, Toast.LENGTH_SHORT).show();
}
});
}
How do I concatenate two arrays in C#?
For smaller arrays <10000 elements:
using System.Linq;
int firstArray = {5,4,2};
int secondArray = {3,2,1};
int[] result = firstArray.ToList().Concat(secondArray.ToList()).toArray();
How do you check what version of SQL Server for a database using TSQL?
CREATE FUNCTION dbo.UFN_GET_SQL_SEVER_VERSION
(
)
RETURNS sysname
AS
BEGIN
DECLARE @ServerVersion sysname, @ProductVersion sysname, @ProductLevel sysname, @Edition sysname;
SELECT @ProductVersion = CONVERT(sysname, SERVERPROPERTY('ProductVersion')),
@ProductLevel = CONVERT(sysname, SERVERPROPERTY('ProductLevel')),
@Edition = CONVERT(sysname, SERVERPROPERTY ('Edition'));
--see: http://support2.microsoft.com/kb/321185
SELECT @ServerVersion =
CASE
WHEN @ProductVersion LIKE '8.00.%' THEN 'Microsoft SQL Server 2000'
WHEN @ProductVersion LIKE '9.00.%' THEN 'Microsoft SQL Server 2005'
WHEN @ProductVersion LIKE '10.00.%' THEN 'Microsoft SQL Server 2008'
WHEN @ProductVersion LIKE '10.50.%' THEN 'Microsoft SQL Server 2008 R2'
WHEN @ProductVersion LIKE '11.0%' THEN 'Microsoft SQL Server 2012'
WHEN @ProductVersion LIKE '12.0%' THEN 'Microsoft SQL Server 2014'
END
RETURN @ServerVersion + N' ('+@ProductLevel + N'), ' + @Edition + ' - ' + @ProductVersion;
END
GO
function declaration isn't a prototype
In C int foo()
and int foo(void)
are different functions. int foo()
accepts an arbitrary number of arguments, while int foo(void)
accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void
consistently when you mean no arguments.
If you have a variable a
, extern int a;
is a way to tell the compiler that a
is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (extern
, static
) only affects its visibility and extern
is the default, so extern
is actually unnecessary.
I suggest removing the extern
, it is extraneous and is usually omitted.
What does "@" mean in Windows batch scripts
It inherits the meaning from DOS. @:
In DOS version 3.3 and later, hides the echo of a batch command. Any output generated by the command is echoed.
Without it, you could turn off command echoing using the echo off
command, but that command would be echoed first.
Java String - See if a string contains only numbers and not letters
import java.util.*;
class Class1 {
public static void main(String[] argh) {
boolean ans = CheckNumbers("123");
if (ans == true) {
System.out.println("String contains numbers only");
} else {
System.out.println("String contains other values as well");
}
}
public static boolean CheckNumbers(String input) {
for (int ctr = 0; ctr < input.length(); ctr++) {
if ("1234567890".contains(Character.valueOf(input.charAt(ctr)).toString())) {
continue;
} else {
return false;
}
}
return true;
}
}
AngularJS check if form is valid in controller
Here is another solution
Set a hidden scope variable in your html then you can use it from your controller:
<span style="display:none" >{{ formValid = myForm.$valid}}</span>
Here is the full working example:
_x000D_
_x000D_
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
$scope.userType = 'guest';_x000D_
$scope.formValid = false;_x000D_
console.info('Ctrl init, no form.');_x000D_
_x000D_
$scope.$watch('myForm', function() {_x000D_
console.info('myForm watch');_x000D_
console.log($scope.formValid);_x000D_
});_x000D_
_x000D_
$scope.isFormValid = function() {_x000D_
//test the new scope variable_x000D_
console.log('form valid?: ', $scope.formValid);_x000D_
};_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
userType: <input name="input" ng-model="userType" required>_x000D_
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
<tt>userType = {{userType}}</tt><br>_x000D_
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
_x000D_
_x000D_
/*-- Hidden Variable formValid to use in your controller --*/_x000D_
<span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
_x000D_
_x000D_
<br/>_x000D_
<button ng-click="isFormValid()">Check Valid</button>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
What is an HttpHandler in ASP.NET
An HttpHandler
(or IHttpHandler
) is basically anything that is responsible for serving content. An ASP.NET page (aspx) is a type of handler.
You might write your own, for example, to serve images etc from a database rather than from the web-server itself, or to write a simple POX service (rather than SOAP/WCF/etc)
Expand Python Search Path to Other Source
There are a few possible ways to do this:
- Set the environment variable
PYTHONPATH
to a colon-separated list of directories to search for imported modules.
- In your program, use
sys.path.append('/path/to/search')
to add the names of directories you want Python to search for imported modules. sys.path
is just the list of directories Python searches every time it gets asked to import a module, and you can alter it as needed (although I wouldn't recommend removing any of the standard directories!). Any directories you put in the environment variable PYTHONPATH
will be inserted into sys.path
when Python starts up.
- Use
site.addsitedir
to add a directory to sys.path
. The difference between this and just plain appending is that when you use addsitedir
, it also looks for .pth
files within that directory and uses them to possibly add additional directories to sys.path
based on the contents of the files. See the documentation for more detail.
Which one of these you want to use depends on your situation. Remember that when you distribute your project to other users, they typically install it in such a manner that the Python code files will be automatically detected by Python's importer (i.e. packages are usually installed in the site-packages
directory), so if you mess with sys.path
in your code, that may be unnecessary and might even have adverse effects when that code runs on another computer. For development, I would venture a guess that setting PYTHONPATH
is usually the best way to go.
However, when you're using something that just runs on your own computer (or when you have nonstandard setups, e.g. sometimes in web app frameworks), it's not entirely uncommon to do something like
import sys
from os.path import dirname
sys.path.append(dirname(__file__))
Printing all global variables/local variables?
In case you want to see the local variables of a calling function use select-frame
before info locals
E.g.:
(gdb) bt
#0 0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1 0xfec36f39 in thr_kill () from /lib/libc.so.1
#2 0xfebe3603 in raise () from /lib/libc.so.1
#3 0xfebc2961 in abort () from /lib/libc.so.1
#4 0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5 0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb)
Change the size of a JTextField inside a JBorderLayout
Try to play with
setMinSize()
setMaxSize()
setPreferredSize()
These method are used by layout when it decide what should be the size of current element. The layout manager calls setSize() and actually overrides your values.
Show or hide element in React
I was able to use css property "hidden". Don't know about possible drawbacks.
export default function App() {
const [hidden, setHidden] = useState(false);
return (
<div>
<button onClick={() => setHidden(!hidden)}>HIDE</button>
<div hidden={hidden}>hidden component</div>
</div>
);
}
SQL Order By Count
Below gives me opposite of what you have. (Notice Group column)
SELECT
*
FROM
myTable
GROUP BY
Group_value,
ID
ORDER BY
count(Group_value)
Let me know if this is fine with you...
I am trying to get what you want too...
SQL Query with Join, Count and Where
SELECT COUNT(*), table1.category_id, table2.category_name
FROM table1
INNER JOIN table2 ON table1.category_id=table2.category_id
WHERE table1.colour <> 'red'
GROUP BY table1.category_id, table2.category_name
Excel- compare two cell from different sheet, if true copy value from other cell
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
- The set fields you want to lookup.
- The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
- This defines what field you want to display upon a match.
- FALSE tells VLOOKUP to do an exact match.
Is there a way to get the git root directory in one command?
Had to solve this myself today. Solved it in C# as I needed it for a program, but I guess it can be esily rewritten. Consider this Public Domain.
public static string GetGitRoot (string file_path) {
file_path = System.IO.Path.GetDirectoryName (file_path);
while (file_path != null) {
if (Directory.Exists (System.IO.Path.Combine (file_path, ".git")))
return file_path;
file_path = Directory.GetParent (file_path).FullName;
}
return null;
}
convert string into array of integers
SO...older thread, I know, but...
EDIT
@RoccoMusolino had a nice catch; here's an alternative:
TL;DR:
const intArray = [...("5 6 7 69 foo 0".split(' ').filter(i => /\d/g.test(i)))]
WRONG: "5 6 note this foo".split(" ").map(Number).filter(Boolean); // [5, 6]
There is a subtle flaw in the more elegant solutions listed here, specifically @amillara and @Marcus' otherwise beautiful answers.
The problem occurs when an element of the string array isn't integer-like, perhaps in a case without validation on an input. For a contrived example...
The problem:
var effedIntArray = "5 6 7 69 foo".split(' ').map(Number); // [5, 6, 7, 69, NaN]
Since you obviously want a PURE int array, that's a problem. Honestly, I didn't catch this until I copy-pasted SO code into my script... :/
The (slightly-less-baller) fix:
var intArray = "5 6 7 69 foo".split(" ").map(Number).filter(Boolean); // [5, 6, 7, 69]
So, now even when you have crap int string, your output is a pure integer array. The others are really sexy in most cases, but I did want to offer my mostly rambly w'actually. It is still a one-liner though, to my credit...
Hope it saves someone time!
Capitalize or change case of an NSString in Objective-C
In case anyone needed the above in swift :
SWIFT 3.0 and above :
this will capitalize your string, make the first letter capital :
viewNoteDateMonth.text = yourString.capitalized
this will uppercase your string, make all the string upper case :
viewNoteDateMonth.text = yourString.uppercased()
wait process until all subprocess finish?
A Popen
object has a .wait()
method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).
If you use this method, you'll prevent that the process zombies are lying around for too long.
(Alternatively, you can use subprocess.call()
or subprocess.check_call()
for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_
)call()
.)
If you have several subprocesses to wait for, you can do
exit_codes = [p.wait() for p in p1, p2]
which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.
How to delete stuff printed to console by System.out.println()?
this solution is applicable if you want to remove some System.out.println() output. It restricts that output to print on console and print other outputs.
PrintStream ps = System.out;
System.setOut(new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {}
}));
System.out.println("It will not print");
//To again enable it.
System.setOut(ps);
System.out.println("It will print");
How do I get a Cron like scheduler in Python?
Another trivial solution would be:
from aqcron import At
from time import sleep
from datetime import datetime
# Event scheduling
event_1 = At( second=5 )
event_2 = At( second=[0,20,40] )
while True:
now = datetime.now()
# Event check
if now in event_1: print "event_1"
if now in event_2: print "event_2"
sleep(1)
And the class aqcron.At is:
# aqcron.py
class At(object):
def __init__(self, year=None, month=None,
day=None, weekday=None,
hour=None, minute=None,
second=None):
loc = locals()
loc.pop("self")
self.at = dict((k, v) for k, v in loc.iteritems() if v != None)
def __contains__(self, now):
for k in self.at.keys():
try:
if not getattr(now, k) in self.at[k]: return False
except TypeError:
if self.at[k] != getattr(now, k): return False
return True
How to break out of multiple loops?
keeplooping=True
while keeplooping:
#Do Stuff
while keeplooping:
#do some other stuff
if finisheddoingstuff():
keeplooping=False
or something like that. You could set a variable in the inner loop, and check it in the outer loop immediately after the inner loop exits, breaking if appropriate. I kinda like the GOTO method, provided you don't mind using an April Fool's joke module - its not Pythonic, but it does make sense.
How to Insert BOOL Value to MySQL Database
TRUE
and FALSE
are keywords, and should not be quoted as strings:
INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);
By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT
in MySQL), which translates into zero for any non-numeric string. Thus, you get 0
for both values in your table.
Non-numeric strings cast to zero:
mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
| 0 | 0 | 12345 |
+------------------------+-------------------------+-------------------------+
But the keywords return their corresponding INT
representation:
mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
| 1 | 0 |
+------+-------+
Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id
with NULL
. The empty string may issue a warning.
How to compare dates in c#
If you have your dates in DateTime variables, they don't have a format.
You can use the Date
property to return a DateTime value with the time portion set to midnight. So, if you have:
DateTime dt1 = DateTime.Parse("07/12/2011");
DateTime dt2 = DateTime.Now;
if(dt1.Date > dt2.Date)
{
//It's a later date
}
else
{
//It's an earlier or equal date
}
Declaring and initializing arrays in C
Why can't you initialize when you declare?
Which C compiler are you using? Does it support C99?
If it does support C99, you can declare the variable where you need it and initialize it when you declare it.
The only excuse I can think of for not doing that would be because you need to declare it but do an early exit before using it, so the initializer would be wasted. However, I suspect that any such code is not as cleanly organized as it should be and could be written so it was not a problem.
What's the difference between a temp table and table variable in SQL Server?
Quote taken from; Professional SQL Server 2012 Internals and Troubleshooting
Statistics
The major difference between temp tables and table variables is that
statistics are not created on table variables. This has two major
consequences, the fi rst of which is that the Query Optimizer uses a
fi xed estimation for the number of rows in a table variable
irrespective of the data it contains. Moreover, adding or removing
data doesn’t change the estimation.
Indexes You can’t create indexes on table variables although you can
create constraints. This means that by creating primary keys or unique
constraints, you can have indexes (as these are created to support
constraints) on table variables. Even if you have constraints, and
therefore indexes that will have statistics, the indexes will not be
used when the query is compiled because they won’t exist at compile
time, nor will they cause recompilations.
Schema Modifications Schema modifications are possible on temporary
tables but not on table variables. Although schema modifi cations are
possible on temporary tables, avoid using them because they cause
recompilations of statements that use the tables.
TABLE VARIABLES ARE NOT CREATED IN MEMORY
There is a common misconception that table variables are in-memory structures
and as such will perform quicker than temporary tables. Thanks to a DMV
called sys . dm _ db _ session _ space _ usage , which shows tempdb usage by
session, you can prove that’s not the case. After restarting SQL Server to clear the
DMV, run the following script to confi rm that your session _ id returns 0 for
user _ objects _ alloc _ page _ count :
SELECT session_id,
database_id,
user_objects_alloc_page_count
FROM sys.dm_db_session_space_usage
WHERE session_id > 50 ;
Now you can check how much space a temporary table uses by running the following
script to create a temporary table with one column and populate it with one row:
CREATE TABLE #TempTable ( ID INT ) ;
INSERT INTO #TempTable ( ID )
VALUES ( 1 ) ;
GO
SELECT session_id,
database_id,
user_objects_alloc_page_count
FROM sys.dm_db_session_space_usage
WHERE session_id > 50 ;
The results on my server indicate that the table was allocated one page in tempdb.
Now run the same script but use a table variable
this time:
DECLARE @TempTable TABLE ( ID INT ) ;
INSERT INTO @TempTable ( ID )
VALUES ( 1 ) ;
GO
SELECT session_id,
database_id,
user_objects_alloc_page_count
FROM sys.dm_db_session_space_usage
WHERE session_id > 50 ;
Which one to Use?
Whether or not you use temporary tables or table variables should be
decided by thorough testing, but it’s best to lean towards temporary
tables as the default because there are far fewer things that can go
wrong.
I’ve seen customers develop code using table variables because they
were dealing with a small amount of rows, and it was quicker than a
temporary table, but a few years later there were hundreds of
thousands of rows in the table variable and performance was terrible,
so try and allow for some capacity planning when you make your
decision!
What's the net::ERR_HTTP2_PROTOCOL_ERROR about?
For several weeks I was also annoyed by this "bug":
net :: ERR_HTTP2_PROTOCOL_ERROR 200
In my case, it occurred on images generated by PHP.
It was at header()
level, and on this one in particular:
header ('Content-Length:'. Filesize($cache_file));
It did obviously not return the exact size, so I deleted it and everything works fine now.
So Chrome checks the accuracy of the data transmitted via the headers, and if it does not correspond, it fails.
EDIT
I found why content-length
via filesize
was being miscalculated: the GZIP
compression is active on the PHP files, so excluding the file in question will fix the problem. Put this code in the .htaccess
:
SetEnvIfNoCase Request_URI ^ / thumb.php no-gzip -vary
It works and we keep the header Content-length
.