Difference between Dictionary and Hashtable
Want to add a difference:
Trying to acess a inexistent key gives runtime error in Dictionary but no problem in hashtable as it returns null instead of error.
e.g.
//No strict type declaration
Hashtable hash = new Hashtable();
hash.Add(1, "One");
hash.Add(2, "Two");
hash.Add(3, "Three");
hash.Add(4, "Four");
hash.Add(5, "Five");
hash.Add(6, "Six");
hash.Add(7, "Seven");
hash.Add(8, "Eight");
hash.Add(9, "Nine");
hash.Add("Ten", 10);// No error as no strict type
for(int i=0;i<=hash.Count;i++)//=>No error for index 0
{
//Can be accessed through indexers
Console.WriteLine(hash[i]);
}
Console.WriteLine(hash["Ten"]);//=> No error in Has Table
here no error for key 0 & also for key "ten"(note: t is small)
//Strict type declaration
Dictionary<int,string> dictionary= new Dictionary<int, string>();
dictionary.Add(1, "One");
dictionary.Add(2, "Two");
dictionary.Add(3, "Three");
dictionary.Add(4, "Four");
dictionary.Add(5, "Five");
dictionary.Add(6, "Six");
dictionary.Add(7, "Seven");
dictionary.Add(8, "Eight");
dictionary.Add(9, "Nine");
//dictionary.Add("Ten", 10);// error as only key, value pair of type int, string can be added
//for i=0, key doesn't exist error
for (int i = 1; i <= dictionary.Count; i++)
{
//Can be accessed through indexers
Console.WriteLine(dictionary[i]);
}
//Error : The given key was not present in the dictionary.
//Console.WriteLine(dictionary[10]);
here error for key 0 & also for key 10 as both are inexistent in dictionary, runtime error, while try to acess.
Java current machine name and logged in user?
To get the currently logged in user:
System.getProperty("user.name"); //platform independent
and the hostname of the machine:
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());
How to close a GUI when I push a JButton?
JButton close = new JButton("Close");
close.addActionListener(this);
public void actionPerformed(ActionEvent closing) {
// getSource() checks for the source of clicked Button , compares with the name of button in which here is close .
if(closing.getSource()==close)
System.exit(0);
// This exit Your GUI
}
/*Some Answers were asking for @override which is overriding the method the super class or the parent class and creating different objects and etc which makes the answer too long . Note : we just need to import java.awt.*; and java.swing.*; and Adding this command : class className implements actionListener{} */
How add unique key to existing table (with non uniques rows)
I am providing my solution with the assumption on your business logic. Basicall in my design i will allow the table to store only one record for a user-game combination. So I will add a composite key to the table.
PRIMARY KEY (`user_id`,`game_id`)
JQuery select2 set default value from an option in list?
One way to accomplish this is...
$('select').select2().select2('val', $('.select2 option:eq(1)').val());
So basically you first initalize the plugin then specify the default value using the 'val' parameter. The actual value is taken from the specified option, in this case #1. So the selected value from this example would be "bar".
<select class=".select2">
<option id="foo">Some Text</option>
<option id="bar">Other Text</option>
</select>
Hope this is useful to someone else.
Python main call within class
Remember, you are NOT allowed to do this.
class foo():
def print_hello(self):
print("Hello") # This next line will produce an ERROR!
self.print_hello() # <---- it calls a class function, inside a class,
# but outside a class function. Not allowed.
You must call a class function from either outside the class, or from within a function in that class.
How to pick an image from gallery (SD Card) for my app?
call chooseImage method like-
public void chooseImage(ImageView v)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if(imageReturnedIntent != null)
{
Uri selectedImage = imageReturnedIntent.getData();
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK)
{
Bitmap datifoto = null;
temp.setImageBitmap(null);
Uri picUri = null;
picUri = imageReturnedIntent.getData();//<- get Uri here from data intent
if(picUri !=null){
try {
datifoto = android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri);
temp.setImageBitmap(datifoto);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (OutOfMemoryError e) {
Toast.makeText(getBaseContext(), "Image is too large. choose other", Toast.LENGTH_LONG).show();
}
}
}
break;
}
}
else
{
//Toast.makeText(getBaseContext(), "data null", Toast.LENGTH_SHORT).show();
}
}
Check if a string has a certain piece of text
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
How can I solve the error LNK2019: unresolved external symbol - function?
Since I want my project to compile to a stand-alone EXE file, I linked the UnitTest project to the function.obj file generated from function.cpp and it works.
Right click on the 'UnitTest1' project ? Configuration Properties ? Linker ? Input ? Additional Dependencies ? add "..\MyProjectTest\Debug\function.obj".
React: how to update state.item[1] in state using setState?
First get the item you want, change what you want on that object and set it back on the state.
The way you're using state by only passing an object in getInitialState
would be way easier if you'd use a keyed object.
handleChange: function (e) {
item = this.state.items[1];
item.name = 'newName';
items[1] = item;
this.setState({items: items});
}
How to make PopUp window in java
The same answer : JOptionpane with an example :)
package experiments;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class CreateDialogFromOptionPane {
public static void main(final String[] args) {
final JFrame parent = new JFrame();
JButton button = new JButton();
button.setText("Click me to show dialog!");
parent.add(button);
parent.pack();
parent.setVisible(true);
button.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String name = JOptionPane.showInputDialog(parent,
"What is your name?", null);
}
});
}
}
Change the color of a checked menu item in a navigation drawer
Step 1: Build a checked/unchecked selector:
selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/yellow" android:state_checked="true" />
<item android:color="@color/white" android:state_checked="false" />
</selector>
Step 2: use the xml attribute app:itemTextColor
within NavigationView
widget for selecting the text color.
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/navigation_header_layout"
app:itemTextColor="@drawable/selector"
app:menu="@menu/navigation_menu" />
Step 3:
For some reason when you hit an item from the NavigationView
menu, it doesn't consider this as a button check. So you need to manually get the selected item checked and clear the previously selected item. Use below listener to do that
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
// remove all colors of the items to the `unchecked` state of the selector
removeColor(mNavigationView);
// check the selected item to change its color set by the `checked` state of the selector
item.setChecked(true);
switch (item.getItemId()) {
case R.id.dashboard:
...
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
private void removeColor(NavigationView view) {
for (int i = 0; i < view.getMenu().size(); i++) {
MenuItem item = view.getMenu().getItem(i);
item.setChecked(false);
}
}
Step 4:
To change icon color, use the app:iconTint
attribute in the NavigationView
menu items, and set to the same selector.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/nav_account"
android:checked="true"
android:icon="@drawable/ic_person_black_24dp"
android:title="My Account"
app:iconTint="@drawable/selector" />
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_settings_black_24dp"
android:title="Settings"
app:iconTint="@drawable/selector" />
<item
android:id="@+id/nav_logout"
android:icon="@drawable/logout"
android:title="Log Out"
app:iconTint="@drawable/selector" />
</menu>
Result:
Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
ContextLoaderListener
has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml
You can customize this by using
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
</context-param>
on web.xml
, or remove this listener if you don't need one.
Simultaneously merge multiple data.frames in a list
Here is a generic wrapper which can be used to convert a binary function to multi-parameters function. The benefit of this solution is that it is very generic and can be applied to any binary functions. You just need to do it once and then you can apply it any where.
To demo the idea, I use simple recursion to implement. It can be of course implemented with more elegant way that benefits from R's good support for functional paradigm.
fold_left <- function(f) {
return(function(...) {
args <- list(...)
return(function(...){
iter <- function(result,rest) {
if (length(rest) == 0) {
return(result)
} else {
return(iter(f(result, rest[[1]], ...), rest[-1]))
}
}
return(iter(args[[1]], args[-1]))
})
})}
Then you can simply wrap any binary functions with it and call with positional parameters (usually data.frames) in the first parentheses and named parameters in the second parentheses (such as by =
or suffix =
). If no named parameters, leave second parentheses empty.
merge_all <- fold_left(merge)
merge_all(df1, df2, df3, df4, df5)(by.x = c("var1", "var2"), by.y = c("var1", "var2"))
left_join_all <- fold_left(left_join)
left_join_all(df1, df2, df3, df4, df5)(c("var1", "var2"))
left_join_all(df1, df2, df3, df4, df5)()
Write a file in UTF-8 using FileWriter (Java)?
Safe Encoding Constructors
Getting Java to properly notify you of encoding errors is tricky. You must use the most verbose and, alas, the least used of the four alternate contructors for each of InputStreamReader
and OutputStreamWriter
to receive a proper exception on an encoding glitch.
For file I/O, always make sure to always use as the second argument to both OutputStreamWriter
and InputStreamReader
the fancy encoder argument:
Charset.forName("UTF-8").newEncoder()
There are other even fancier possibilities, but none of the three simpler possibilities work for exception handing. These do:
OutputStreamWriter char_output = new OutputStreamWriter(
new FileOutputStream("some_output.utf8"),
Charset.forName("UTF-8").newEncoder()
);
InputStreamReader char_input = new InputStreamReader(
new FileInputStream("some_input.utf8"),
Charset.forName("UTF-8").newDecoder()
);
As for running with
$ java -Dfile.encoding=utf8 SomeTrulyRemarkablyLongcLassNameGoeShere
The problem is that that will not use the full encoder argument form for the character streams, and so you will again miss encoding problems.
Longer Example
Here’s a longer example, this one managing a process instead of a file, where we promote two different input bytes streams and one output byte stream all to UTF-8 character streams with full exception handling:
// this runs a perl script with UTF-8 STD{IN,OUT,ERR} streams
Process
slave_process = Runtime.getRuntime().exec("perl -CS script args");
// fetch his stdin byte stream...
OutputStream
__bytes_into_his_stdin = slave_process.getOutputStream();
// and make a character stream with exceptions on encoding errors
OutputStreamWriter
chars_into_his_stdin = new OutputStreamWriter(
__bytes_into_his_stdin,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newEncoder()
);
// fetch his stdout byte stream...
InputStream
__bytes_from_his_stdout = slave_process.getInputStream();
// and make a character stream with exceptions on encoding errors
InputStreamReader
chars_from_his_stdout = new InputStreamReader(
__bytes_from_his_stdout,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newDecoder()
);
// fetch his stderr byte stream...
InputStream
__bytes_from_his_stderr = slave_process.getErrorStream();
// and make a character stream with exceptions on encoding errors
InputStreamReader
chars_from_his_stderr = new InputStreamReader(
__bytes_from_his_stderr,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newDecoder()
);
Now you have three character streams that all raise exception on encoding errors, respectively called chars_into_his_stdin
, chars_from_his_stdout
, and chars_from_his_stderr
.
This is only slightly more complicated that what you need for your problem, whose solution I gave in the first half of this answer. The key point is this is the only way to detect encoding errors.
Just don’t get me started about PrintStream
s eating exceptions.
How to find out whether a file is at its `eof`?
Reading a file in batches of BATCH_SIZE
lines (the last batch can be shorter):
BATCH_SIZE = 1000 # lines
with open('/path/to/a/file') as fin:
eof = False
while eof is False:
# We use an iterator to check later if it was fully realized. This
# is a way to know if we reached the EOF.
# NOTE: file.tell() can't be used with iterators.
batch_range = iter(range(BATCH_SIZE))
acc = [line for (_, line) in zip(batch_range, fin)]
# DO SOMETHING WITH "acc"
# If we still have something to iterate, we have read the whole
# file.
if any(batch_range):
eof = True
What are the new features in C++17?
Language features:
Templates and Generic Code
Lambda
Attributes
Syntax cleanup
Cleaner multi-return and flow control
Misc
Hexadecimal float point literals
Dynamic memory allocation for over-aligned data
Guaranteed copy elision
- Finally!
- Not in all cases, but distinguishes syntax where you are "just creating something" that was called elision, from "genuine elision".
Fixed order-of-evaluation for (some) expressions with some modifications
- Not including function arguments, but function argument evaluation interleaving now banned
- Makes a bunch of broken code work mostly, and makes
.then
on future work.
Direct list-initialization of enums
Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
- I think this is saying "the implementation may not stall threads forever"?
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
"noexcept" in the type system
__has_include
- Test if a header file include would be an error
- makes migrating from experimental to std almost seamless
Arrays of pointer conversion fixes
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
aggregate initialization with inheritance.
std::launder
, type punning, etc
Library additions:
Data types
Invoke stuff
std::invoke
- Call any callable (function pointer, function, member pointer) with one syntax. From the standard INVOKE concept.
std::apply
- Takes a function-like and a tuple, and unpacks the tuple into the call.
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
Threading
Container Improvements
Smart pointer changes
Other std
datatype improvements:
Misc
C++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
destroy(_at|_n)
, uninitialized_move(_n)
, uninitialized_value_construct(_n)
, uninitialized_default_construct(_n)
- utility code already in most
std
implementations exposed
- Special math functions
std::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughly
gcd
and lcm
std::uncaught_exceptions
- Required if you want to only throw if safe from destructors
std::as_const
std::bool_constant
- A whole bunch of
_v
template variables
std::void_t<T>
- Surprisingly useful when writing templates
std::owner_less<void>
- like
std::less<void>
, but for smart pointers to sort based on contents
std::chrono
polish
std::conjunction
, std::disjunction
, std::negation
exposed
std::not_fn
- Rules for noexcept within
std
- std::is_contiguous_layout, useful for efficient hashing
- std::to_chars/std::from_chars, high performance, locale agnostic number conversion; finally a way to serialize/deserialize to human readable formats (JSON & co)
std::default_order, indirection over std::less
. (breaks ABI of some compilers due to name mangling, removed.)
Traits
Deprecated
Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
Removed:
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
Papers not yet integrated into above:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
Spec changes:
Further reference:
Intent.putExtra List
//To send from the activity that is calling another activity via myIntent
myIntent.putExtra("id","10");
startActivity(myIntent);
//To receive from another Activity
Bundle bundle = getIntent().getExtras();
String id=bundle.getString("id");
Printing Lists as Tabular Data
>>> import pandas
>>> pandas.DataFrame(data, teams_list, teams_list)
Man Utd Man City T Hotspur
Man Utd 1 2 1
Man City 0 1 0
T Hotspur 2 4 2
How can I echo a newline in a batch file?
Here you go, create a .bat file with the following in it :
@echo off
REM Creating a Newline variable (the two blank lines are required!)
set NLM=^
set NL=^^^%NLM%%NLM%^%NLM%%NLM%
REM Example Usage:
echo There should be a newline%NL%inserted here.
echo.
pause
You should see output like the following:
There should be a newline
inserted here.
Press any key to continue . . .
You only need the code between the REM statements, obviously.
Get method arguments using Spring AOP?
If you have to log all args or your method have one argument, you can simply use getArgs like described in previous answers.
If you have to log a specific arg, you can annoted it and then recover its value like this :
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Data {
String methodName() default "";
}
@Aspect
public class YourAspect {
@Around("...")
public Object around(ProceedingJoinPoint point) throws Throwable {
Method method = MethodSignature.class.cast(point.getSignature()).getMethod();
Object[] args = point.getArgs();
StringBuilder data = new StringBuilder();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int argIndex = 0; argIndex < args.length; argIndex++) {
for (Annotation paramAnnotation : parameterAnnotations[argIndex]) {
if (!(paramAnnotation instanceof Data)) {
continue;
}
Data dataAnnotation = (Data) paramAnnotation;
if (dataAnnotation.methodName().length() > 0) {
Object obj = args[argIndex];
Method dataMethod = obj.getClass().getMethod(dataAnnotation.methodName());
data.append(dataMethod.invoke(obj));
continue;
}
data.append(args[argIndex]);
}
}
}
}
Examples of use :
public void doSomething(String someValue, @Data String someData, String otherValue) {
// Apsect will log value of someData param
}
public void doSomething(String someValue, @Data(methodName = "id") SomeObject someData, String otherValue) {
// Apsect will log returned value of someData.id() method
}
What column type/length should I use for storing a Bcrypt hashed password in a Database?
If you are using PHP's password_hash()
with the PASSWORD_DEFAULT
algorithm to generate the bcrypt hash (which I would assume is a large percentage of people reading this question) be sure to keep in mind that in the future password_hash()
might use a different algorithm as the default and this could therefore affect the length of the hash (but it may not necessarily be longer).
From the manual page:
Note that this constant is designed to change over time as new and
stronger algorithms are added to PHP. For that reason, the length of
the result from using this identifier can change over time. Therefore,
it is recommended to store the result in a database column that can
expand beyond 60 characters (255 characters would be a good choice).
Using bcrypt, even if you have 1 billion users (i.e. you're currently competing with facebook) to store 255 byte password hashes it would only ~255 GB of data - about the size of a smallish SSD hard drive. It is extremely unlikely that storing the password hash is going to be the bottleneck in your application. However in the off chance that storage space really is an issue for some reason, you can use PASSWORD_BCRYPT
to force password_hash()
to use bcrypt, even if that's not the default. Just be sure to stay informed about any vulnerabilities found in bcrypt and review the release notes every time a new PHP version is released. If the default algorithm is ever changed it would be good to review why and make an informed decision whether to use the new algorithm or not.
html5 - canvas element - Multiple layers
but layer 02, will cover all drawings in layer 01. I used this to show drawing in both layers. use (background-color: transparent;) in style.
_x000D_
_x000D_
<div style="position: relative;"> _x000D_
<canvas id="lay01" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 0; background-color: transparent;">_x000D_
</canvas> _x000D_
<canvas id="lay02" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 1; background-color: transparent;">_x000D_
</canvas>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How do I export (and then import) a Subversion repository?
Excerpt from my Blog-Note-to-myself:
Now you can import a dump file e.g. if you are migrating between machines / subversion versions. e.g. if I had created a dump file from the source repository and load it into the new repository as shown below.
Commands for Unix-like systems (from terminal):
svnadmin dump /path/to/your/old/repo > backup.dump
svnadmin load /path/to/your/new/repo < backup.dump.dmp
Commands for Microsoft Windows systems (from cmd shell):
svnadmin dump C:\path\to\your\old\repo > backup.dump
svnadmin load C:\path\to\your\old\repo < backup.dump
CentOS 64 bit bad ELF interpreter
Just came across the same problem on a freshly installed CentOS 6.4 64-bit machine. A single yum command will fix this plus 99% of similar problems:
yum groupinstall "Compatibility libraries"
Either prefix this with 'sudo' or run as root, whichever works best for you.
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
What's the purpose of SQL keyword "AS"?
When you aren't sure which syntax to choose, especially when there doesn't seem to be much to separate the choices, consult a book on heuristics. As far as I know, the only heuristics book for SQL is 'Joe Celko's SQL Programming Style':
A correlation name is more often
called an alias, but I will be formal.
In SQL-92, they can have an optional
AS
operator, and it should be used
to make it clear that something is
being given a new name. [p16]
This way, if your team doesn't like the convention, you can blame Celko -- I know I do ;)
UPDATE 1: IIRC for a long time, Oracle did not support the AS
(preceding correlation name) keyword, which may explain why some old timers don't use it habitually.
UPDATE 2: the term 'correlation name', although used by the SQL Standard, is inappropriate. The underlying concept is that of a ‘range variable’.
UPDATE 3: I just re-read what Celko wrote and he is wrong: the table is not being renamed! I now think:
A correlation name is more often called an alias, but I will be formal. In Standard SQL they can have an optional AS
keyword but it should not be used because it may give the impression that something is being renamed when it is not. In fact, it should be omitted to enforce the point that it is a range variable.
SQL select statements with multiple tables
You need to join the two tables:
select p.id, p.first, p.middle, p.last, p.age,
a.id as address_id, a.street, a.city, a.state, a.zip
from Person p inner join Address a on p.id = a.person_id
where a.zip = '97229';
This will select all of the columns from both tables. You could of course limit that by choosing different columns in the select
clause.
How to convert string to boolean php
If your "boolean" variable comes from a global array such as $_POST and $_GET, you can use filter_input()
filter function.
Example for POST:
$isSleeping = filter_input(INPUT_POST, 'is_sleeping', FILTER_VALIDATE_BOOLEAN);
If your "boolean" variable comes from other source you can use filter_var()
filter function.
Example:
filter_var('true', FILTER_VALIDATE_BOOLEAN); // true
Will iOS launch my app into the background if it was force-quit by the user?
I've been trying different variants of this for days, and I thought for a day I had it re-launching the app in the background, even when the user swiped to kill, but no I can't replicate that behavior.
It's unfortunate that the behavior is quite different than before. On iOS 6, if you killed the app from the jiggling icons, it would still get re-awoken on SLC triggers. Now, if you kill by swiping, that doesn't happen.
It's a different behavior, and the user, who would continue to get useful information from our app if they had killed it on iOS 6, now will not.
We need to nudge our users to re-open the app now if they have swiped to kill it and are still expecting some of the notification behavior that we used to give them. I'm worried this won't be obvious to users when they swipe an app away. They may, after all, be basically cleaning up or wanting to rearrange the apps that are shown minimized.
Getting A File's Mime Type In Java
I couldn't find anything to check for video/mp4
MIME type so I made my own solution.
I happened to observe that Wikipedia was wrong and that the 00 00 00 18 66 74 79 70 69 73 6F 6D
file signature is not correct. the fourth byte (18
) and all 70
(excluded) after changes quite a lot amongst otherwise valid mp4
files.
This code is essentially a copy/paste of URLConnection.guessContentTypeFromStream
code but tailored to video/mp4
.
BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content));
String mimeType = URLConnection.guessContentTypeFromStream(bis);
// Goes full barbaric and processes the bytes manually
if (mimeType == null){
// These ints converted in hex ar:
// 00 00 00 18 66 74 79 70 69 73 6F 6D
// which are the file signature (magic bytes) for .mp4 files
// from https://www.wikiwand.com/en/List_of_file_signatures
// just ctrl+f "mp4"
int[] mp4_sig = {0, 0, 0, 24, 102, 116, 121, 112};
bis.reset();
bis.mark(16);
int[] firstBytes = new int[8];
for (int i = 0; i < 8; i++) {
firstBytes[i] = bis.read();
}
// This byte doesn't matter for the file signature and changes
mp4_sig[3] = content[3];
bis.reset();
if (Arrays.equals(firstBytes, mp4_sig)){
mimeType = "video/mp4";
}
}
Tested successfully against 10 different .mp4
files.
EDIT: Here is a useful link (if it is still online) where you can find samples of many types. I don't own those videos, don't know who does either, but they're useful for testing the above code.
HTML table with fixed headers and a fixed column?
The first column has a scrollbar on the cell right below the headers
<table>
<thead>
<th> Header 1</th>
<th> Header 2</th>
<th> Header 3</th>
</thead>
<tbody>
<tr>
<td>
<div style="width: 50; height:30; overflow-y: scroll">
Tklasdjf alksjf asjdfk jsadfl kajsdl fjasdk fljsaldk
fjlksa djflkasjdflkjsadlkf jsakldjfasdjfklasjdflkjasdlkfjaslkdfjasdf
</div>
</td>
<td>
Hello world
</td>
<td> Hello world2
</tr>
</tbody>
</table>
Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux
As of the Windows 10 "Anniversary" update (Version 1607), you can now run an Ubuntu subsystem from directly inside of Windows by enabling a feature called Developer mode.
To enable developer mode, go to Start > Settings then typing "Use developer features" in the search box to find the setting. On the left hand navigation, you will then see a tab titled For developers. From within this tab, you will see a radio box to enable Developer mode.
After developer mode is enabled, you will then be able to enable the Linux subsystem feature. To do so, go to Control Panel > Programs > Turn Windows features on or off > and check the box that says Windows Subsystem for Linux (Beta)
Now, rather than using Cygwin or a console emulator, you can run tmux through bash on the Ubuntu subsystem directly from Windows through the traditional apt package (sudo apt-get install tmux
).
Cannot open output file, permission denied
The problem is related to Sam´s response:
"have encountered the same problem you have. I found that it may have
some relationship with the way you terminate your run result. When you
run your code, whether it has a printout, the debugger will call the
console which print a "Press any key to continue...". If you terminate
the console by pressing key, it's ok; if you do it by click the close
button, the problem comes as you described. When you terminate it in
the latter way, you have to wait several minutes before you can
rebuild your code."
Avoid kill processes, and we have two choices, wait until the process release the .EXE file or this problem will be solved faster restarting the IDE.
Export to xls using angularjs
$scope.ExportExcel= function () { //function define in html tag
//export to excel file
var tab_text = '<table border="1px" style="font-size:20px" ">';
var textRange;
var j = 0;
var tab = document.getElementById('TableExcel'); // id of table
var lines = tab.rows.length;
// the first headline of the table
if (lines > 0) {
tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
}
// table data lines, loop starting from 1
for (j = 1 ; j < lines; j++) {
tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</tr>";
}
tab_text = tab_text + "</table>";
tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, ""); //remove if u want links in your table
tab_text = tab_text.replace(/<img[^>]*>/gi, ""); // remove if u want images in your table
tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
// console.log(tab_text); // aktivate so see the result (press F12 in browser)
var fileName = 'report.xls'
var exceldata = new Blob([tab_text], { type: "application/vnd.ms-excel;charset=utf-8" })
if (window.navigator.msSaveBlob) { // IE 10+
window.navigator.msSaveOrOpenBlob(exceldata, fileName);
//$scope.DataNullEventDetails = true;
} else {
var link = document.createElement('a'); //create link download file
link.href = window.URL.createObjectURL(exceldata); // set url for link download
link.setAttribute('download', fileName); //set attribute for link created
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
//html of button
Bash ignoring error for a particular command
If you want to prevent your script failing and collect the return code:
command () {
return 1 # or 0 for success
}
set -e
command && returncode=$? || returncode=$?
echo $returncode
returncode
is collected no matter whether command succeeds or fails.
Changing ImageView source
myImgView.setImageResource(R.drawable.monkey);
is used for setting image in the current image view, but if want to delete this image
then you can use this code like:
((ImageView) v.findViewById(R.id.ImageView1)).setImageResource(0);
now this will delete the image from your image view, because it has set the resources value to zero.
Add and remove multiple classes in jQuery
Add multiple classes:
$("p").addClass("class1 class2 class3");
or in cascade:
$("p").addClass("class1").addClass("class2").addClass("class3");
Very similar also to remove more classes:
$("p").removeClass("class1 class2 class3");
or in cascade:
$("p").removeClass("class1").removeClass("class2").removeClass("class3");
How to execute INSERT statement using JdbcTemplate class from Spring Framework
If you use spring-boot, you don't need to create a DataSource class, just specify the data url/username/password/driver in application.properties
, then you can simply @Autowired
it.
@Repository
public class JdbcRepository {
private final JdbcTemplate jdbcTemplate;
@Autowired
public DynamicRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void insert() {
jdbcTemplate.update("INSERT INTO BOOK (name, description) VALUES ('book name', 'book description')");
}
}
Example of application.properties
:
#Basic Spring Boot Config for Oracle
spring.datasource.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YourHostIP)(PORT=YourPort))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=YourServiceName)))
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
Then add the driver and connection pool dependencies in pom.xml
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.1</version>
</dependency>
<!-- HikariCP connection pool -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.0</version>
</dependency>
See the official doc for more details.
Not unique table/alias
Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.
Try
SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
FROM Project_Assigned pa
INNER JOIN Account a
ON pa.AccountID = a.Account_ID
INNER JOIN Project p
ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
ON a.Account_ID = c.Account_ID
WHERE a.Access_Type = 'Client';
conflicting types for 'outchar'
In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:
#include <stdio.h> #include <stdlib.h> void outchar(char ch); int main() { outchar('A'); outchar('B'); outchar('C'); return 0; } void outchar(char ch) { printf("%c", ch); }
Also, you should be specifying the return type of every function. I added that for you.
No content to map due to end-of-input jackson parser
I had a similar error today and the issue was the content-type header of the post request. Make sure the content type is what you expect. In my case a multipart/form-data
content-type header was being sent to the API instead of application/json
.
String formatting in Python 3
That line works as-is in Python 3.
>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'
How to receive JSON as an MVC 5 action method parameter
You are sending a array of string
var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
So change model type accordingly
public ActionResult AddUser(List<string> model)
{
}
How to compare numbers in bash?
The bracket stuff (e.g., [[ $a -gt $b ]]
or (( $a > $b ))
) isn't enough if you want to use float numbers as well; it would report a syntax error. If you want to compare float numbers or float number to integer, you can use (( $(bc <<< "...") ))
.
For example,
a=2.00
b=1
if (( $(bc <<<"$a > $b") )); then
echo "a is greater than b"
else
echo "a is not greater than b"
fi
You can include more than one comparison in the if statement. For example,
a=2.
b=1
c=1.0000
if (( $(bc <<<"$b == $c && $b < $a") )); then
echo "b is equal to c but less than a"
else
echo "b is either not equal to c and/or not less than a"
fi
That's helpful if you want to check if a numeric variable (integer or not) is within a numeric range.
SQL sum with condition
Try this instead:
SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)
Explanation
Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:
The CASE expression has two formats:
- The simple CASE expression compares an expression to a set of simple expressions to determine the result.
- The searched CASE expression evaluates a set of Boolean expressions to determine the result.
You want the searched CASE expression syntax:
CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.
Best Practices for mapping one object to another
/// <summary>
/// map properties
/// </summary>
/// <param name="sourceObj"></param>
/// <param name="targetObj"></param>
private void MapProp(object sourceObj, object targetObj)
{
Type T1 = sourceObj.GetType();
Type T2 = targetObj.GetType();
PropertyInfo[] sourceProprties = T1.GetProperties(BindingFlags.Instance | BindingFlags.Public);
PropertyInfo[] targetProprties = T2.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var sourceProp in sourceProprties)
{
object osourceVal = sourceProp.GetValue(sourceObj, null);
int entIndex = Array.IndexOf(targetProprties, sourceProp);
if (entIndex >= 0)
{
var targetProp = targetProprties[entIndex];
targetProp.SetValue(targetObj, osourceVal);
}
}
}
What does the function then() mean in JavaScript?
I am about 8 years late, well...anyways, I don't really know what then() does but maybe MDN might have an answer. Actually, I might actually understand it a little more.
This will show you all the information (hopefully), you need. Unless someone already posted this link.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
The format is promise.prototype.then()
The promise and prototype are kind of like variables but not like variables in javascript, I mean like other things go there like navigator.getBattery().then() where this one actually exists but is barely used on the web, this one shows statuses about the battery of the device, more information and more on MDN if you are curious.
Java Generics With a Class & an Interface - Together
You can't do it with "anonymous" type parameters (ie, wildcards that use ?
), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.
import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
T t;
}
Remove innerHTML from div
var $div = $('#desiredDiv');
$div.contents().remove();
$div.html('<p>This is new HTML.</p>');
That should work just fine.
How to convert image to byte array
If you don't reference the imageBytes to carry bytes in the stream, the method won't return anything. Make sure you reference imageBytes = m.ToArray();
public static byte[] SerializeImage() {
MemoryStream m;
string PicPath = pathToImage";
byte[] imageBytes;
using (Image image = Image.FromFile(PicPath)) {
using ( m = new MemoryStream()) {
image.Save(m, image.RawFormat);
imageBytes = new byte[m.Length];
//Very Important
imageBytes = m.ToArray();
}//end using
}//end using
return imageBytes;
}//SerializeImage
EF Core add-migration Build Failed
I had exact same error but I am using Visual Studio Community 2017 Version 15.2 (26430.14) to build .Net Core projects.
I have a ASP.NET Core MVC web project and a separate security project using ASP.NET Core Identity. The web project contains connection string in aspsettings.json config file.
I also installed Bundler & Minifier and Web Essentials 2017 extensions in Visual Studio so that I can compile, minify and bundle my assets and put them to wwwroot.
I figured out it was the MSBuild those 2 extensions secretly download that caused the problem, because I had Enable Bundle on Build and Enable Compile on Build on. After I disable that, everything works fine.
Probably not the cause to your problem, but might be worthy to just give it a try.
Convert Date/Time for given Timezone - java
We can handle this by using offset value
public static long convertDateTimeZone(long lngDate, String fromTimeZone,
String toTimeZone){
TimeZone toTZ = TimeZone.getTimeZone(toTimeZone);
Calendar toCal = Calendar.getInstance(toTZ);
TimeZone fromTZ = TimeZone.getTimeZone(fromTimeZone);
Calendar fromCal = Calendar.getInstance(fromTZ);
fromCal.setTimeInMillis(lngDate);
toCal.setTimeInMillis(fromCal.getTimeInMillis()
+ toTZ.getOffset(fromCal.getTimeInMillis())
- TimeZone.getDefault().getOffset(fromCal.getTimeInMillis()));
return toCal.getTimeInMillis();
}
Test Code snippet:
System.out.println(new Date().getTime())
System.out.println(convertDateTimeZone(new Date().getTime(), TimeZone
.getDefault().getID(), "EST"));
Output:
1387353270742
1387335270742
How to read file contents into a variable in a batch file?
To get all the lines of the file loaded into the variable, Delayed Expansion is needed, so do the following:
SETLOCAL EnableDelayedExpansion
for /f "Tokens=* Delims=" %%x in (version.txt) do set Build=!Build!%%x
There is a problem with some special characters, though especially ;
, %
and !
'typeid' versus 'typeof' in C++
Answering the additional question:
my following test code for typeid does
not output the correct type name.
what's wrong?
There isn't anything wrong. What you see is the string representation of the type name. The standard C++ doesn't force compilers to emit the exact name of the class, it is just up to the implementer(compiler vendor) to decide what is suitable. In short, the names are up to the compiler.
These are two different tools. typeof
returns the type of an expression, but it is not standard. In C++0x there is something called decltype
which does the same job AFAIK.
decltype(0xdeedbeef) number = 0; // number is of type int!
decltype(someArray[0]) element = someArray[0];
Whereas typeid
is used with polymorphic types. For example, lets say that cat
derives animal
:
animal* a = new cat; // animal has to have at least one virtual function
...
if( typeid(*a) == typeid(cat) )
{
// the object is of type cat! but the pointer is base pointer.
}
Disallow Twitter Bootstrap modal window from closing
Override the Bootstrap ‘hide’ event of Dialog and stop its default behavior (to dispose the dialog).
Please see the below code snippet:
$('#yourDialogID').on('hide.bs.modal', function(e) {
e.preventDefault();
});
It works fine in our case.
Trigger event when user scroll to specific element - with jQuery
Combining this question with the best answer from jQuery trigger action when a user scrolls past a certain part of the page
var element_position = $('#scroll-to').offset().top;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = element_position;
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}
});
UPDATE
I've improved the code so that it will trigger when the element is half way up the screen rather than at the very top. It will also trigger the code if the user hits the bottom of the screen and the function hasn't fired yet.
var element_position = $('#scroll-to').offset().top;
var screen_height = $(window).height();
var activation_offset = 0.5;//determines how far up the the page the element needs to be before triggering the function
var activation_point = element_position - (screen_height * activation_offset);
var max_scroll_height = $('body').height() - screen_height - 5;//-5 for a little bit of buffer
//Does something when user scrolls to it OR
//Does it when user has reached the bottom of the page and hasn't triggered the function yet
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if(element_in_view || has_reached_bottom_of_page) {
//Do something
}
});
How can I determine the direction of a jQuery scroll event?
Keep it super simple:
jQuery Event Listener Way:
$(window).on('wheel', function(){
whichDirection(event);
});
Vanilla JavaScript Event Listener Way:
if(window.addEventListener){
addEventListener('wheel', whichDirection, false);
} else if (window.attachEvent) {
attachEvent('wheel', whichDirection, false);
}
Function Remains The Same:
function whichDirection(event){
console.log(event + ' WheelEvent has all kinds of good stuff to work with');
var scrollDirection = event.deltaY;
if(scrollDirection === 1){
console.log('meet me at the club, going down', scrollDirection);
} else if(scrollDirection === -1) {
console.log('Going up, on a tuesday', scrollDirection);
}
}
I wrote a more indepth post on it here
???????
How can I get an HTTP response body as a string?
Here's a lightweight way to do so:
String responseString = "";
for (int i = 0; i < response.getEntity().getContentLength(); i++) {
responseString +=
Character.toString((char)response.getEntity().getContent().read());
}
With of course responseString
containing website's response and response being type of HttpResponse
, returned by HttpClient.execute(request)
onActivityResult is not being called in Fragment
Inside your fragment, call
this.startActivityForResult(intent, REQUEST_CODE);
where this
is referring to the fragment. Otherwise do as @Clevester said:
Fragment fragment = this;
....
fragment.startActivityForResult(intent, REQUEST_CODE);
I also had to call
super.onActivityResult(requestCode, resultCode, data);
in the parent activity's onActivityResult
to make it work.
(I adapted this answer from @Clevester's answer.)
What does \0 stand for?
It means '\0' is a NULL
character in C, don't know about Objective-C
but its probably the same.
ini_set("memory_limit") in PHP 5.3.3 is not working at all
Ubuntu 10.04 comes with the Suhosin patch only, which does not give you configuration options. But you can install php5-suhosin to solve this:
apt-get update
apt-get install php5-suhosin
Now you can edit /etc/php5/conf.d/suhosin.ini and set:
suhosin.memory_limit = 1G
Then using ini_set will work in a script:
ini_set('memory_limit', '256M');
How to upload files on server folder using jsp
You cannot upload like this.
http://grand-shopping.com/<"some folder">
You need a physical path exactly like in your local
C:/Users/puneet verma/Downloads/
What you can do is create some local path where your server is working. Hence you can store and retrieve the file. If you bought some domain from any websites there will be path to upload the files. You create these variable as static constant and use it based on the server you are working (Local/Website).
How do I Search/Find and Replace in a standard string?
Why not implement your own replace?
void myReplace(std::string& str,
const std::string& oldStr,
const std::string& newStr)
{
std::string::size_type pos = 0u;
while((pos = str.find(oldStr, pos)) != std::string::npos){
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
PHP date time greater than today
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Demo
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
Demo
Is there a CSS selector by class prefix?
It's not doable with CSS2.1, but it is possible with CSS3 attribute substring-matching selectors (which are supported in IE7+):
div[class^="status-"], div[class*=" status-"]
Notice the space character in the second attribute selector. This picks up div
elements whose class
attribute meets either of these conditions:
[class^="status-"]
— starts with "status-"
[class*=" status-"]
— contains the substring "status-" occurring directly after a space character. Class names are separated by whitespace per the HTML spec, hence the significant space character. This checks any other classes after the first if multiple classes are specified, and adds a bonus of checking the first class in case the attribute value is space-padded (which can happen with some applications that output class
attributes dynamically).
Naturally, this also works in jQuery, as demonstrated here.
The reason you need to combine two attribute selectors as described above is because an attribute selector such as [class*="status-"]
will match the following element, which may be undesirable:
<div id='D' class='foo-class foo-status-bar bar-class'></div>
If you can ensure that such a scenario will never happen, then you are free to use such a selector for the sake of simplicity. However, the combination above is much more robust.
If you have control over the HTML source or the application generating the markup, it may be simpler to just make the status-
prefix its own status
class instead as Gumbo suggests.
Simplest/cleanest way to implement a singleton in JavaScript
A singleton in JavaScript is achieved using the module pattern and closures.
Below is the code which is pretty much self-explanatory -
// Singleton example.
var singleton = (function() {
var instance;
function init() {
var privateVar1 = "this is a private variable";
var privateVar2 = "another var";
function pubMethod() {
// Accessing private variables from inside.
console.log(this.privateVar1);
console.log(this.privateVar2);
console.log("inside of a public method");
};
}
function getInstance() {
if (!instance) {
instance = init();
}
return instance;
};
return {
getInstance: getInstance
}
})();
var obj1 = singleton.getInstance();
var obj2 = singleton.getInstance();
console.log(obj1 === obj2); // Check for type and value.
What does flex: 1 mean?
Here is the explanation:
https://www.w3.org/TR/css-flexbox-1/#flex-common
flex: <positive-number>
Equivalent to flex: <positive-number> 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that
receives the specified proportion of the free space in the flex
container. If all items in the flex container use this pattern, their
sizes will be proportional to the specified flex factor.
Therefore flex:1
is equivalent to flex: 1 1 0
What is the difference between ports 465 and 587?
SMTP protocol: smtps (port 465) v. msa (port 587)
Ports 465 and 587 are intended for email client to email server communication - sending out email using SMTP protocol.
Port 465 is for smtps
SSL encryption is started automatically before any SMTP level communication.
Port 587 is for msa
It is almost like standard SMTP port.
MSA should accept email after authentication (e.g. after SMTP AUTH). It helps to stop outgoing spam when netmasters of DUL ranges can block outgoing connections to SMTP port (port 25).
SSL encryption may be started by STARTTLS command at SMTP level if server supports it and your ISP does not filter server's EHLO reply (reported 2014).
Port 25 is used by MTA to MTA communication (mail server to mail server). It may be used for client to server communication but it is not currently the most recommended. Standard SMTP port accepts email from other mail servers to its "internal" mailboxes without authentication.
A tool to convert MATLAB code to Python
There are several tools for converting Matlab to Python code.
The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).
Other options include:
- LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
- OMPC: Matlab to Python (a bit outdated).
Also, for those interested in an interface between the two languages and not conversion:
pymatlab
: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
- Python-Matlab wormholes: both directions of interaction supported.
- Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
- PyMat: Control Matlab session from Python.
pymat2
: continuation of the seemingly abandoned PyMat.
mlabwrap
, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
oct2py
: run GNU Octave commands from within Python.
pymex
: Embeds the Python Interpreter in Matlab, also on File Exchange.
matpy
: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
- MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.
Btw might be helpful to look here for other migration tips:
On a different note, though I'm not a fortran
fan at all, for people who might find it useful there is:
Execute Stored Procedure from a Function
Functions are not allowed to have side-effects such as altering table contents.
Stored Procedures are.
If a function called a stored procedure, the function would become able to have side-effects.
So, sorry, but no, you can't call a stored procedure from a function.
How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?
Since C++11 std::regex_search
can also be used to provide even more complex expressions matching. The following example handles also floating numbers thorugh std::stof
and a subsequent cast to int
.
However the parseInt
method shown below could throw a std::invalid_argument
exception if the prefix is not matched; this can be easily adapted depending on the given application:
#include <iostream>
#include <regex>
int parseInt(const std::string &str, const std::string &prefix) {
std::smatch match;
std::regex_search(str, match, std::regex("^" + prefix + "([+-]?(?=\\.?\\d)\\d*(?:\\.\\d*)?(?:[Ee][+-]?\\d+)?)$"));
return std::stof(match[1]);
}
int main() {
std::cout << parseInt("foo=13.3", "foo=") << std::endl;
std::cout << parseInt("foo=-.9", "foo=") << std::endl;
std::cout << parseInt("foo=+13.3", "foo=") << std::endl;
std::cout << parseInt("foo=-0.133", "foo=") << std::endl;
std::cout << parseInt("foo=+00123456", "foo=") << std::endl;
std::cout << parseInt("foo=-06.12e+3", "foo=") << std::endl;
// throw std::invalid_argument
// std::cout << parseInt("foo=1", "bar=") << std::endl;
return 0;
}
The kind of magic of the regex pattern is well detailed in the following answer.
EDIT: the previous answer did not performed the conversion to integer.
how to insert a new line character in a string to PrintStream then use a scanner to re-read the file
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
Can I access constants in settings.py from templates in Django?
I like Berislav's solution, because on simple sites, it is clean and effective. What I do NOT like is exposing all the settings constants willy-nilly. So what I ended up doing was this:
from django import template
from django.conf import settings
register = template.Library()
ALLOWABLE_VALUES = ("CONSTANT_NAME_1", "CONSTANT_NAME_2",)
# settings value
@register.simple_tag
def settings_value(name):
if name in ALLOWABLE_VALUES:
return getattr(settings, name, '')
return ''
Usage:
{% settings_value "CONSTANT_NAME_1" %}
This protects any constants that you have not named from use in the template, and if you wanted to get really fancy, you could set a tuple in the settings, and create more than one template tag for different pages, apps or areas, and simply combine a local tuple with the settings tuple as needed, then do the list comprehension to see if the value is acceptable.
I agree, on a complex site, this is a bit simplistic, but there are values that would be nice to have universally in templates, and this seems to work nicely.
Thanks to Berislav for the original idea!
What is base 64 encoding used for?
The usage of Base64 I'm going to describe here is somewhat a hack. So if you don't like hacks, please do not go on.
I went into trouble when I discovered that MySQL's utf8 does not support 4-byte unicode characters since it uses a 3-byte version of utf8. So what I did to support full 4-byte unicode over MySQL's utf8? Well, base64 encode strings when storing into the database and base64 decode when retrieving.
Since base64 encoding and decoding is very fast, the above worked perfectly.
You have the following points to take note of:
You could use the above method for any storage engine that does not support unicode.
How do I turn a C# object into a JSON string in .NET?
Serializer
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite, new JsonSerializerSettings
{
Formatting = Formatting.Indented,
});
using (var writer = new StreamWriter(filePath, append))
{
writer.Write(contentsToWriteToFile);
}
}
Object
namespace MyConfig
{
public class AppConfigurationSettings
{
public AppConfigurationSettings()
{
/* initialize the object if you want to output a new document
* for use as a template or default settings possibly when
* an app is started.
*/
if (AppSettings == null) { AppSettings=new AppSettings();}
}
public AppSettings AppSettings { get; set; }
}
public class AppSettings
{
public bool DebugMode { get; set; } = false;
}
}
Implementation
var jsonObject = new AppConfigurationSettings();
WriteToJsonFile<AppConfigurationSettings>(file.FullName, jsonObject);
Output
{
"AppSettings": {
"DebugMode": false
}
}
How to change the ROOT application?
I'll look at my docs; there's a way of specifying a configuration to change the path of the root web application away from ROOT (or ROOT.war), but it seems to have changed between Tomcat 5 and 6.
Found this:
http://www.nabble.com/Re:-Tomcat-6-and-ROOT-application...-td20017401.html
So, it seems that changing the root path (in ROOT.xml) is possible, but a bit broken -- you need to move your WAR outside of the auto-deployment directory. Mind if I ask why just renaming your file to ROOT.war isn't a workable solution?
How to get bitmap from a url in android?
Okay so you are trying to get a bitmap from a file? Title says URL. Anyways, when you are getting files from external storage in Android you should never use a direct path. Instead call getExternalStorageDirectory() like so:
File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE);
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile);
getExternalStorageDirectory() gives you the path to the SD card.
Also you need to declare the WRITE_EXTERNAL_STORAGE permission in the Manifest.
How to see the CREATE VIEW code for a view in PostgreSQL?
GoodNews from v.9.6 and above, View editing are now native from psql. Just invoke \ev
command. View definitions will show in your configured editor.
julian@assange=# \ev {your_view_names}
Bonus. Some useful command to interact with query buffer.
Query Buffer
\e [FILE] [LINE] edit the query buffer (or file) with external editor
\ef [FUNCNAME [LINE]] edit function definition with external editor
\ev [VIEWNAME [LINE]] edit view definition with external editor
\p show the contents of the query buffer
\r reset (clear) the query buffer
\s [FILE] display history or save it to file
\w FILE write query buffer to file
Printing out all the objects in array list
Whenever you print any instance of your class, the default
toString
implementation of Object
class is called, which returns the representation that you are getting.
It contains two parts: - Type
and Hashcode
So, in student.Student@82701e that you get as output ->
student.Student
is the Type
, and
82701e
is the HashCode
So, you need to override a toString
method in your Student
class to get required String representation
: -
@Override
public String toString() {
return "Student No: " + this.getStudentNo() +
", Student Name: " + this.getStudentName();
}
So, when from your main
class, you print your ArrayList
, it will invoke the toString
method for each instance, that you overrided
rather than the one in Object
class: -
List<Student> students = new ArrayList();
// You can directly print your ArrayList
System.out.println(students);
// Or, iterate through it to print each instance
for(Student student: students) {
System.out.println(student); // Will invoke overrided `toString()` method
}
In both the above cases, the toString
method overrided in Student
class will be invoked and appropriate representation of each instance will be printed.
How do I parse JSON with Objective-C?
JSON parsing using NSJSONSerialization
NSString* path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
//Here you can take JSON string from your URL ,I am using json file
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
NSLog(@"jsonDataArray: %@",jsonDataArray);
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];
if(jsonObject !=nil){
// NSString *errorCode=[NSMutableString stringWithFormat:@"%@",[jsonObject objectForKey:@"response"]];
if(![[jsonObject objectForKey:@"#data"] isEqual:@""]){
NSMutableArray *array=[jsonObject objectForKey:@"#data"];
// NSLog(@"array: %@",array);
NSLog(@"array: %d",array.count);
int k = 0;
for(int z = 0; z<array.count;z++){
NSString *strfd = [NSString stringWithFormat:@"%d",k];
NSDictionary *dicr = jsonObject[@"#data"][strfd];
k=k+1;
// NSLog(@"dicr: %@",dicr);
NSLog(@"Firstname - Lastname : %@ - %@",
[NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_first_name"]],
[NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_last_name"]]);
}
}
}
You can see the Console output as below :
Firstname - Lastname : Chandra Bhusan - Pandey
Firstname - Lastname : Kalaiyarasan - Balu
Firstname - Lastname : (null) - (null)
Firstname - Lastname : Girija - S
Firstname - Lastname : Girija - S
Firstname - Lastname : (null) - (null)
How do I execute a file in Cygwin?
Thomas wrote:
Apparently, gcc doesn't behave like the one described in The C Programming language
It does in general. For your program to run on Windows it needs to end in .exe, "the C Programming language" was not written with Windows programmers in mind. As you've seen, cygwin emulates many, but not all, features of a POSIX environment.
Why does git perform fast-forward merges by default?
Let me expand a bit on a VonC's very comprehensive answer:
First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.
Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".
Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.
HTH
What are the best PHP input sanitizing functions?
Sanitizers
Sanitize is a function to check (and remove) harmful data from user input which can harm the software.
Sanitizing user input is the most secure method of user input validation to strip out anything that is not on the whitelist.
PHP Support
5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.27, 7.4.0 - 7.4.15, 8.0.0 - 8.0.2
<?php
require_once("path/to/Sanitizers.php");
use Sanitizers\Sanitizers\Sanitizer;
\\ passing `true` in Sanitizer class enables exceptions
$sanitize = new Sanitizer(true);
try {
echo $sanitize->Username($_GET['username']);
} catch (Exception $e) {
echo "Could not Sanitize user input."
var_dump($e);
}
?>
Download the latest release
See Sanitizers GitHub project.
How to overcome root domain CNAME restrictions?
The reason this question still often arises is because, as you mentioned, somewhere somehow someone presumed as important wrote that the RFC states domain names without subdomain in front of them are not valid. If you read the RFC carefully, however, you'll find that this is not exactly what it says. In fact, RFC 1912 states:
Don't go overboard with CNAMEs. Use them when renaming hosts, but plan to get rid of them (and inform your users).
Some DNS hosts provide a way to get CNAME-like functionality at the zone apex (the root domain level, for the naked domain name) using a custom record type. Such records include, for example:
- ALIAS at DNSimple
- ANAME at DNS Made Easy
- ANAME at easyDNS
- CNAME at CloudFlare
For each provider, the setup is similar: point the ALIAS or ANAME entry for your apex domain to example.domain.com, just as you would with a CNAME record.
Depending on the DNS provider, an empty or @ Name value identifies the zone apex.
ALIAS or ANAME or @ example.domain.com.
If your DNS provider does not support such a record-type, and you are unable to switch to one that does, you will need to use subdomain redirection, which is not that hard, depending on the protocol or server software that needs to do it.
I strongly disagree with the statement that it's done only by "amateur admins" or such ideas. It's a simple "What does the name and its service need to do?" deal, and then to adapt your DNS config to serve those wishes; If your main services are web and e-mail, I don' t see any VALID reason why dropping the CNAMEs for-good would be problematic. After all, who would prefer @subdomain.domain.org over @domain.org ? Who needs "www" if you're already set with the protocol itself? It's illogical to assume that use of a root-domainname would be invalid.
how to draw smooth curve through N points using javascript HTML5 canvas?
If you want to determine the equation of the curve through n points then the following code will give you the coefficients of the polynomial of degree n-1 and save these coefficients to the coefficients[]
array (starting from the constant term). The x coordinates do not have to be in order. This is an example of a Lagrange polynomial.
var xPoints=[2,4,3,6,7,10]; //example coordinates
var yPoints=[2,5,-2,0,2,8];
var coefficients=[];
for (var m=0; m<xPoints.length; m++) coefficients[m]=0;
for (var m=0; m<xPoints.length; m++) {
var newCoefficients=[];
for (var nc=0; nc<xPoints.length; nc++) newCoefficients[nc]=0;
if (m>0) {
newCoefficients[0]=-xPoints[0]/(xPoints[m]-xPoints[0]);
newCoefficients[1]=1/(xPoints[m]-xPoints[0]);
} else {
newCoefficients[0]=-xPoints[1]/(xPoints[m]-xPoints[1]);
newCoefficients[1]=1/(xPoints[m]-xPoints[1]);
}
var startIndex=1;
if (m==0) startIndex=2;
for (var n=startIndex; n<xPoints.length; n++) {
if (m==n) continue;
for (var nc=xPoints.length-1; nc>=1; nc--) {
newCoefficients[nc]=newCoefficients[nc]*(-xPoints[n]/(xPoints[m]-xPoints[n]))+newCoefficients[nc-1]/(xPoints[m]-xPoints[n]);
}
newCoefficients[0]=newCoefficients[0]*(-xPoints[n]/(xPoints[m]-xPoints[n]));
}
for (var nc=0; nc<xPoints.length; nc++) coefficients[nc]+=yPoints[m]*newCoefficients[nc];
}
Add column to SQL query results
why dont you add a "source" column to each of the queries with a static value like
select 'source 1' as Source, column1, column2...
from table1
UNION ALL
select 'source 2' as Source, column1, column2...
from table2
How to get correlation of two vectors in python
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
SQL Error: ORA-00913: too many values
If you are having 112 columns in one single table and you would like to insert data from source table, you could do as
create table employees as select * from source_employees where employee_id=100;
Or from sqlplus do as
copy from source_schema/password insert employees using select * from
source_employees where employee_id=100;
The most efficient way to remove first N elements in a list?
l = [1, 2, 3, 4, 5]
del l[0:3] # Here 3 specifies the number of items to be deleted.
This is the code if you want to delete a number of items from the list. You might as well skip the zero before the colon. It does not have that importance. This might do as well.
l = [1, 2, 3, 4, 5]
del l[:3] # Here 3 specifies the number of items to be deleted.
How to import an existing project from GitHub into Android Studio
In Github click the "Clone or download" button of the project you want to import --> download the ZIP file and unzip it. In Android Studio Go to File -> New Project -> Import Project and select the newly unzipped folder -> press OK. It will build the Gradle automatically.
Good Luck with your project
Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"
I know I'm 4 years late but my answer is for anyone who may not have figured it out. I'm using a Samsung Galaxy S6, what worked for me was:
Disable USB debugging
Disable Developer mode
Unplug the device from the USB cable
Re-enable Developer mode
Re-enable USB debugging
Reconnect the USB cable to your device
It is important you do it in this order as it didn't work until it was done in this order.
Can I nest a <button> element inside an <a> using HTML5?
No, it isn't valid HTML5 according to the HTML5 Spec Document from W3C:
Content model: Transparent, but there must be no interactive content descendant.
The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links).
In other words, you can nest any elements inside an <a>
except the following:
<a>
<audio>
(if the controls attribute is present)
<button>
<details>
<embed>
<iframe>
<img>
(if the usemap attribute is present)
<input>
(if the type attribute is not in the hidden state)
<keygen>
<label>
<menu>
(if the type attribute is in the toolbar state)
<object>
(if the usemap attribute is present)
<select>
<textarea>
<video>
(if the controls attribute is present)
If you are trying to have a button that links to somewhere, wrap that button inside a <form>
tag as such:
<form style="display: inline" action="http://example.com/" method="get">
<button>Visit Website</button>
</form>
However, if your <button>
tag is styled using CSS and doesn't look like the system's widget... Do yourself a favor, create a new class for your <a>
tag and style it the same way.
How to present popover properly in iOS 8
I found a complete example of how to get this all to work so that you can always display a popover no matter the device/orientation https://github.com/frogcjn/AdaptivePopover_iOS8_Swift.
The key is to implement UIAdaptivePresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(PC: UIPresentationController!) -> UIModalPresentationStyle {
// This *forces* a popover to be displayed on the iPhone
return .None
}
Then extend the example above (from Imagine Digital):
nav.popoverPresentationController!.delegate = implOfUIAPCDelegate
Bootstrap modal link
Please remove . from your target it should be a id
<a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>
Also you have to give your modal id like below
<div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">
Here is the solution in a fiddle.
Selecting multiple items in ListView
In listView you can use it by Adapter
ArrayAdapter<String> adapterChannels = new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice);
How to add shortcut keys for java code in eclipse
This is one more option: go to Windows > Preference > Java > Editor > Content Assit. Look in "Auto Activation" zone, sure that "Enable auto activation" is checked and add more charactor (like "abcd....yz, default is ".") to auto show content assist menu as your typing.
What is the difference between a function expression vs declaration in JavaScript?
Function Declaration
function foo() { ... }
Because of function hoisting, the function declared this way can be called both after and before the definition.
Function Expression
Named Function Expression
var foo = function bar() { ... }
Anonymous Function Expression
var foo = function() { ... }
foo()
can be called only after creation.
(function() { ... }());
Conclusion
Crockford recommends to use function expression because it makes it clear that foo
is a variable containing a function value. Well, personally, I prefer to use Declaration unless there is a reason for Expression.
Calling Java from Python
If you're in Python 3, there's a fork of JPype called JPype1-py3
pip install JPype1-py3
This works for me on OSX / Python 3.4.3. (You may need to export JAVA_HOME=/Library/Java/JavaVirtualMachines/your-java-version
)
from jpype import *
startJVM(getDefaultJVMPath(), "-ea")
java.lang.System.out.println("hello world")
shutdownJVM()
How to implement Rate It feature in Android App
My one using DialogFragment:
public class RateItDialogFragment extends DialogFragment {
private static final int LAUNCHES_UNTIL_PROMPT = 10;
private static final int DAYS_UNTIL_PROMPT = 3;
private static final int MILLIS_UNTIL_PROMPT = DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000;
private static final String PREF_NAME = "APP_RATER";
private static final String LAST_PROMPT = "LAST_PROMPT";
private static final String LAUNCHES = "LAUNCHES";
private static final String DISABLED = "DISABLED";
public static void show(Context context, FragmentManager fragmentManager) {
boolean shouldShow = false;
SharedPreferences sharedPreferences = getSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
long currentTime = System.currentTimeMillis();
long lastPromptTime = sharedPreferences.getLong(LAST_PROMPT, 0);
if (lastPromptTime == 0) {
lastPromptTime = currentTime;
editor.putLong(LAST_PROMPT, lastPromptTime);
}
if (!sharedPreferences.getBoolean(DISABLED, false)) {
int launches = sharedPreferences.getInt(LAUNCHES, 0) + 1;
if (launches > LAUNCHES_UNTIL_PROMPT) {
if (currentTime > lastPromptTime + MILLIS_UNTIL_PROMPT) {
shouldShow = true;
}
}
editor.putInt(LAUNCHES, launches);
}
if (shouldShow) {
editor.putInt(LAUNCHES, 0).putLong(LAST_PROMPT, System.currentTimeMillis()).commit();
new RateItDialogFragment().show(fragmentManager, null);
} else {
editor.commit();
}
}
private static SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences(PREF_NAME, 0);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.rate_title)
.setMessage(R.string.rate_message)
.setPositiveButton(R.string.rate_positive, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getActivity().getPackageName())));
getSharedPreferences(getActivity()).edit().putBoolean(DISABLED, true).commit();
dismiss();
}
})
.setNeutralButton(R.string.rate_remind_later, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
})
.setNegativeButton(R.string.rate_never, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getSharedPreferences(getActivity()).edit().putBoolean(DISABLED, true).commit();
dismiss();
}
}).create();
}
}
Then use it in onCreate()
of your main FragmentActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
RateItDialogFragment.show(this, getFragmentManager());
}
How can I use the HTML5 canvas element in IE?
I just used flashcanvas, and I got that working. If you encounter problems, just make sure to read the caveats and whatnot. Particularly, if you create canvas elements dynamically, you need to initialize them explicitly:
if (typeof FlashCanvas != "undefined") {
FlashCanvas.initElement(canvas);
}
SecurityError: Blocked a frame with origin from accessing a cross-origin frame
I would like to add Java Spring specific configuration that can effect on this.
In Web site or Gateway application there is a contentSecurityPolicy setting
in Spring you can find implementation of WebSecurityConfigurerAdapter sub class
contentSecurityPolicy("
script-src 'self' [URLDomain]/scripts ;
style-src 'self' [URLDomain]/styles;
frame-src 'self' [URLDomain]/frameUrl...
...
.referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
Browser will be blocked if you have not define safe external contenet here.
How can I clone an SQL Server database on the same server in SQL Server 2008 Express?
Using MS SQL Server 2012, you need to perform 3 basic steps:
First, generate .sql
file containing only the structure of the source DB
- right click on the source DB and then Tasks then Generate Scripts
- follow the wizard and save the
.sql
file locally
Second, replace the source DB with the destination one in the .sql
file
- Right click on the destination file, select New Query and Ctrl-H or (Edit - Find and replace - Quick replace)
Finally, populate with data
- Right click on the destination DB, then select Tasks and Import Data
- Data source drop down set to ".net framework data provider for SQL server" + set the connection string text field under DATA ex:
Data Source=Mehdi\SQLEXPRESS;Initial Catalog=db_test;User ID=sa;Password=sqlrpwrd15
- do the same with the destination
- check the table you want to transfer or check box besides "source: ..." to check all of them
You are done.
Difference between break and continue statement
First,i think you should know that there are two types of break and continue in Java which are labeled break,unlabeled break,labeled continue and unlabeled continue.Now, i will talk about the difference between them.
class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts =
{ 32, 87, 3, 589,
12, 1076, 2000,
8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;//this is an unlabeled break,an unlabeled break statement terminates the innermost switch,for,while,do-while statement.
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at index " + i);
} else {
System.out.println(searchfor + " not in the array");
}
}
An unlabeled break statement terminates the innermost switch ,for ,while ,do-while statement.
public class BreakWithLabelDemo {
public static void main(String[] args) {
search:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.println(i + " - " + j);
if (j == 3)
break search;//this is an labeled break.To notice the lab which is search.
}
}
}
A labeled break terminates an outer statement.if you javac and java this demo,you will get:
0 - 0
0 - 1
0 - 2
0 - 3
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
// interested only in p's
if (searchMe.charAt(i) != 'p')
continue;//this is an unlabeled continue.
// process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
An unlabeled continue statement skips the current iteration of a for,while,do-while statement.
public class ContinueWithLabelDemo {
public static void main(String[] args) {
search:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.println(i + " - " + j);
if (j == 3)
continue search;//this is an labeled continue.Notice the lab which is search
}
}
}
A labeled continue statement skips the current iteration of an outer loop marked with the given lable,if you javac and java the demo,you will get:
0 - 0
0 - 1
0 - 2
0 - 3
1 - 0
1 - 1
1 - 2
1 - 3
2 - 0
2 - 1
2 - 2
2 - 3
if you have any question , you can see the Java tutorial of this:enter link description here
Live Video Streaming with PHP
I am not saying that you have to abandon PHP, but you need different technologies here.
Let's start off simple (without Akamai :-)) and think about the implications here. Video, chat, etc. - it's all client-side in the beginning. The user has a webcam, you want to grab the signal somehow and send it to the server. There is no PHP so far.
I know that Flash supports this though (check this tutorial on webcams and flash) so you could use Flash to transport the content to the server. I think if you'll stay with Flash, then Flex (flex and webcam tutorial) is probably a good idea to look into.
So those are just the basics, maybe it gives you an idea of where you need to research because obviously this won't give you a full video chat inside your app yet. For starters, you will need some sort of way to record the streams and re-publish them so others see other people from the chat, etc..
I'm also not sure how much traffic and bandwidth this is gonna consume though and generally, you will need way more than a Stackoverflow question to solve this issue. Best would be to do a full spec of your app and then hire some people to help you build it.
HTH!
Finding the max/min value in an array of primitives using Java
Using Commons Lang (to convert) + Collections (to min/max)
import java.util.Arrays;
import java.util.Collections;
import org.apache.commons.lang.ArrayUtils;
public class MinMaxValue {
public static void main(String[] args) {
char[] a = {'3', '5', '1', '4', '2'};
List b = Arrays.asList(ArrayUtils.toObject(a));
System.out.println(Collections.min(b));
System.out.println(Collections.max(b));
}
}
Note that Arrays.asList()
wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.
Bash write to file without echo?
The way to do this in bash is
zsh <<< '> test <<< "Hello World!"'
This is one of the interesting differences between zsh and bash: given an unchained >
or >>
, zsh has the good sense to hook it up to stdin, while bash does not. It would be downright useful - if it were only standard.
I tried to use this to send & append my ssh key over ssh to a remote authorized_keys
file, but the remote host was bash, of course, and quietly did nothing.
And that's why you should just use cat
.
Installing cmake with home-brew
Download the latest CMake Mac binary distribution here: https://cmake.org/download/
(current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
How to set UTF-8 encoding for a PHP file
PHP, by default, always returns the following header: "Content-Type: text/html" (notice no charset), therefore you must use
<?php header('Content-type: text/plain; charset=utf-8'); ?>
How to add "active" class to wp_nav_menu() current menu item (simple way)
If you want the 'active' in the html:
header with html and php:
<?php
$menu_items = wp_get_nav_menu_items( 'main_nav' ); // id or name of menu
foreach ( (array) $menu_items as $key => $menu_item ) {
if ( ! $menu_item->menu_item_parent ) {
echo "<li class=" . vince_check_active_menu($menu_item) . "><a href='$menu_item->url'>";
echo $menu_item->title;
echo "</a></li>";
}
}
?>
functions.php:
function vince_check_active_menu( $menu_item ) {
$actual_link = ( isset( $_SERVER['HTTPS'] ) ? "https" : "http" ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if ( $actual_link == $menu_item->url ) {
return 'active';
}
return '';
}
use current date as default value for a column
To use the current date as the default for a date column, you will need to:
1- open table designer
2- select the column
3- go to column proprerties
4- set the value of Default value or binding propriete To (getdate())
What's the purpose of META-INF?
Adding to the information here, the META-INF is a special folder which the ClassLoader
treats differently from other folders in the jar.
Elements nested inside the META-INF folder are not mixed with the elements outside of it.
Think of it like another root. From the Enumerator<URL> ClassLoader#getSystemResources(String path)
method et al perspective:
When the given path starts with "META-INF", the method searches for resources that are nested inside the META-INF folders of all the jars in the class path.
When the given path doesn't start with "META-INF", the method searches for resources in all the other folders (outside the META-INF) of all the jars and directories in the class path.
If you know about another folder name that the getSystemResources
method treats specially, please comment about it.
Continuous Integration vs. Continuous Delivery vs. Continuous Deployment
DevOps is a combination of 3C's - continuous, communication, collaboration and this lead to prime focus in various industries.
In an IoT connected devices world, multiple scrum features like product owner, web, mobile and QA working in an agile manner in a scrum of scrum cycle to deliver a product to end customer.
Continuous integration: Multiple scrum feature working simultanrouly in multiple endpoints
Continuous delivery: With integration and deployment, delivery of product to multiple customers to be handled at the same time.
Continuous deployment: multiple products deployed to multiple customers at multiple platform.
Watch this to know how DevOps enabling IoT connected world: https://youtu.be/nAfZt2t4HqA
Doctrine and LIKE query
you can also do it like that :
$ver = $em->getRepository('GedDocumentBundle:version')->search($val);
$tail = sizeof($ver);
Xcode 6 Storyboard the wrong size?
If you are using Xcode 6 and designing for iOS 8, none of these solutions are correct. To get your iPhone-only views to be sized correctly, don't turn off size classes, don't turn off inferred metrics, and don't set constraints (yet). Instead, use the size class control, which is an easy to miss text button at the bottom of Interface Builder that initially reads "wAny hAny".
Click the button, and choose Compact Width, Regular Height. This resize your views and cover all iPhone portrait orientations.
Apple's docs here: https://developer.apple.com/library/ios/recipes/xcode_help-IB_adaptive_sizes/chapters/SelectingASizeClass.html or search on "Selecting a Size Class in Interface Builder"
Laravel Advanced Wheres how to pass variable into function?
You can pass the necessary variables from the parent scope into the closure with the use
keyword.
For example:
DB::table('users')->where(function ($query) use ($activated) {
$query->where('activated', '=', $activated);
})->get();
More on that here.
EDIT (2019 update):
PHP 7.4 (will be released at November 28, 2019) introduces a shorter variation of the anonymous functions called arrow functions which makes this a bit less verbose.
An example using PHP 7.4 which is functionally nearly equivalent (see the 3rd bullet point below):
DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated))->get();
Differences compared to the regular syntax:
fn
keyword instead of function
.
- No need to explicitly list all variables which should be captured from the parent scope - this is now done automatically by-value. See the lack of
use
keyword in the latter example.
- Arrow functions always return a value. This also means that it's impossible to use
void
return type when declaring them.
- The
return
keyword must be omitted.
- Arrow functions must have a single expression which is the return statement. Multi-line functions aren't supported at the moment. You can still chain methods though.
How to install SQL Server Management Studio 2008 component only
If you have the SQL Server 2008 Installation media, you can install just the Client/Workstation Components. You don't have to install the database engine to install the workstation tools, but if you plan to do Integration Services development, you do need to install the Integration Services Engine on the workstation for BIDS to be able to be used for development. Keep in mind that Visual Studio 2010 does not have BI development support currently, so you have to install BIDS from the SQL Installation media and use the Visual Studio 2008 BI Development Studio that installs under the SQL Server 2008 folder in Program Files if you need to do any SSIS, SSRS, or SSAS development from the workstation.
As mentioned in the comments you can download Management Studio Express free from Microsoft, but if you already have the installation media for SQL Server Standard/Enterprise/Developer edition, you'd be better off using what you have.
Download SSMS 2008 Express
How can you print a variable name in python?
If you are trying to do this, it means you are doing something wrong. Consider using a dict
instead.
def show_val(vals, name):
print "Name:", name, "val:", vals[name]
vals = {'a': 1, 'b': 2}
show_val(vals, 'b')
Output:
Name: b val: 2
Java, Shifting Elements in an Array
public class Test1 {
public static void main(String[] args) {
int[] x = { 1, 2, 3, 4, 5, 6 };
Test1 test = new Test1();
x = test.shiftArray(x, 2);
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
public int[] pushFirstElementToLast(int[] x, int position) {
int temp = x[0];
for (int i = 0; i < x.length - 1; i++) {
x[i] = x[i + 1];
}
x[x.length - 1] = temp;
return x;
}
public int[] shiftArray(int[] x, int position) {
for (int i = position - 1; i >= 0; i--) {
x = pushFirstElementToLast(x, position);
}
return x;
}
}
How to get current time in python and break up into year, month, day, hour, minute?
By unpacking timetuple
of datetime object, you should get what you want:
from datetime import datetime
n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t
Return file in ASP.Net Core Web API
Here is a simplistic example of streaming a file:
using System.IO;
using Microsoft.AspNetCore.Mvc;
[HttpGet("{id}")]
public async Task<FileStreamResult> Download(int id)
{
var path = "<Get the file path using the ID>";
var stream = File.OpenRead(path);
return new FileStreamResult(stream, "application/octet-stream");
}
Note:
Be sure to use FileStreamResult
from Microsoft.AspNetCore.Mvc
and not from System.Web.Mvc
.
Singleton: How should it be used
The problem with singletons is not their implementation. It is that they conflate two different concepts, neither of which is obviously desirable.
1) Singletons provide a global access mechanism to an object. Although they might be marginally more threadsafe or marginally more reliable in languages without a well-defined initialization order, this usage is still the moral equivalent of a global variable. It's a global variable dressed up in some awkward syntax (foo::get_instance() instead of g_foo, say), but it serves the exact same purpose (a single object accessible across the entire program) and has the exact same drawbacks.
2) Singletons prevent multiple instantiations of a class. It's rare, IME, that this kind of feature should be baked into a class. It's normally a much more contextual thing; a lot of the things that are regarded as one-and-only-one are really just happens-to-be-only-one. IMO a more appropriate solution is to just create only one instance--until you realize that you need more than one instance.
ListAGG in SQLSERVER
This might be useful to someone also ..
i.e. For a data analyst and data profiling type of purposes ..(i.e. not grouped by) ..
Prior to the SQL*Server 2017 String_agg function existence ..
(i.e. returns just one row ..)
select distinct
SUBSTRING (
stuff(( select distinct ',' + [FieldB] from tablename order by 1 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
,1,0,'' )
,2,9999)
from
tablename
e.g. returns comma separated values
A,B
SQL Server String Concatenation with Null
In Sql Server:
insert into Table_Name(PersonName,PersonEmail) values(NULL,'[email protected]')
PersonName is varchar(50), NULL is not a string, because we are not passing with in single codes, so it treat as NULL.
Code Behind:
string name = (txtName.Text=="")? NULL : "'"+ txtName.Text +"'";
string email = txtEmail.Text;
insert into Table_Name(PersonName,PersonEmail) values(name,'"+email+"')
ConvergenceWarning: Liblinear failed to converge, increase the number of iterations
I reached the point that I set, up to max_iter=1200000
on my LinearSVC
classifier, but still the "ConvergenceWarning" was still present. I fix the issue by just setting dual=False
and leaving max_iter
to its default.
With LogisticRegression(solver='lbfgs')
classifier, you should increase max_iter
. Mine have reached max_iter=7600
before the "ConvergenceWarning" disappears when training with large dataset's features.
Writing outputs to log file and console
Yes, you want to use tee
:
tee - read from standard input and write to standard output and files
Just pipe your command to tee and pass the file as an argument, like so:
exec 1 | tee ${LOG_FILE}
exec 2 | tee ${LOG_FILE}
This both prints the output to the STDOUT and writes the same output to a log file. See man tee
for more information.
Note that this won't write stderr to the log file, so if you want to combine the two streams then use:
exec 1 2>&1 | tee ${LOG_FILE}
Bootstrap 3 Align Text To Bottom of Div
The easiest way I have tested just add a <br>
as in the following:
<div class="col-sm-6">
<br><h3><p class="text-center">Some Text</p></h3>
</div>
The only problem is that a extra line break (generated by that <br>
) is generated when the screen gets smaller and it stacks. But it is quick and simple.
Concatenating two std::vectors
To be honest, you could fast concatenate two vectors by copy elements from two vectors into the other one or just only append one of two vectors!. It depends on your aim.
Method 1: Assign new vector with its size is the sum of two original vectors' size.
vector<int> concat_vector = vector<int>();
concat_vector.setcapacity(vector_A.size() + vector_B.size());
// Loop for copy elements in two vectors into concat_vector
Method 2: Append vector A by adding/inserting elements of vector B.
// Loop for insert elements of vector_B into vector_A with insert()
function: vector_A.insert(vector_A .end(), vector_B.cbegin(), vector_B.cend());
$http.get(...).success is not a function
If you are trying to use AngularJs 1.6.6 as of 21/10/2017 the following parameter works as .success and has been depleted. The .then() method takes two arguments: a response and an error callback which will be called with a response object.
$scope.login = function () {
$scope.btntext = "Please wait...!";
$http({
method: "POST",
url: '/Home/userlogin', // link UserLogin with HomeController
data: $scope.user
}).then(function (response) {
console.log("Result value is : " + parseInt(response));
data = response.data;
$scope.btntext = 'Login';
if (data == 1) {
window.location.href = '/Home/dashboard';
}
else {
alert(data);
}
}, function (error) {
alert("Failed Login");
});
The above snipit works for a login page.
Determine the number of NA values in a column
A tidyverse way to count the number of nulls in every column of a dataframe:
library(tidyverse)
library(purrr)
df %>%
map_df(function(x) sum(is.na(x))) %>%
gather(feature, num_nulls) %>%
print(n = 100)
Sorting HTML table with JavaScript
Another approach to sort HTML table. (based on W3.JS HTML Sort)
_x000D_
_x000D_
var collection = [{_x000D_
"Country": "France",_x000D_
"Date": "2001-01-01",_x000D_
"Size": "25",_x000D_
}, {_x000D_
"Country": "spain",_x000D_
"Date": "2005-05-05",_x000D_
"Size": "",_x000D_
}, {_x000D_
"Country": "Lebanon",_x000D_
"Date": "2002-02-02",_x000D_
"Size": "-17",_x000D_
}, {_x000D_
"Country": "Argentina",_x000D_
"Date": "2005-04-04",_x000D_
"Size": "100",_x000D_
}, {_x000D_
"Country": "USA",_x000D_
"Date": "",_x000D_
"Size": "-6",_x000D_
}]_x000D_
_x000D_
for (var j = 0; j < 3; j++) {_x000D_
$("#myTable th:eq(" + j + ")").addClass("control-label clickable");_x000D_
$("#myTable th:eq(" + j + ")").attr('onClick', "w3.sortHTML('#myTable', '.item', 'td:nth-child(" + (j + 1) + ")')");_x000D_
}_x000D_
_x000D_
$tbody = $("#myTable").append('<tbody></tbody>');_x000D_
_x000D_
for (var i = 0; i < collection.length; i++) {_x000D_
$tbody = $tbody.append('<tr class="item"><td>' + collection[i]["Country"] + '</td><td>' + collection[i]["Date"] + '</td><td>' + collection[i]["Size"] + '</td></tr>');_x000D_
}
_x000D_
.control-label:after {_x000D_
content: "*";_x000D_
color: red;_x000D_
}_x000D_
_x000D_
.clickable {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="myTable" class="w3-table-all">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Country</th>_x000D_
<th>Date</th>_x000D_
<th>Size</th>_x000D_
</tr>_x000D_
</thead>_x000D_
</table>
_x000D_
_x000D_
_x000D_
How to retrieve a user environment variable in CMake (Windows)
Environment variables (that you modify using the System Properties) are only propagated to subshells when you create a new subshell.
If you had a command line prompt (DOS or cygwin) open when you changed the User env vars, then they won't show up.
You need to open a new command line prompt after you change the user settings.
The equivalent in Unix/Linux is adding a line to your .bash_rc: you need to start a new shell to get the values.
Python Requests library redirect new url
This is answering a slightly different question, but since I got stuck on this myself, I hope it might be useful for someone else.
If you want to use allow_redirects=False
and get directly to the first redirect object, rather than following a chain of them, and you just want to get the redirect location directly out of the 302 response object, then r.url
won't work. Instead, it's the "Location" header:
r = requests.get('http://github.com/', allow_redirects=False)
r.status_code # 302
r.url # http://github.com, not https.
r.headers['Location'] # https://github.com/ -- the redirect destination
Calling Oracle stored procedure from C#?
Connecting to Oracle is ugly. Here is some cleaner code with a using statement. A lot of the other samples don't call the IDisposable Methods on the objects they create.
using (OracleConnection connection = new OracleConnection("ConnectionString"))
using (OracleCommand command = new OracleCommand("ProcName", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("ParameterName", OracleDbType.Varchar2).Value = "Your Data Here";
command.Parameters.Add("SomeOutVar", OracleDbType.Varchar2, 120);
command.Parameters["return_out"].Direction = ParameterDirection.Output;
command.Parameters.Add("SomeOutVar1", OracleDbType.Varchar2, 120);
command.Parameters["return_out2"].Direction = ParameterDirection.Output;
connection.Open();
command.ExecuteNonQuery();
string SomeOutVar = command.Parameters["SomeOutVar"].Value.ToString();
string SomeOutVar1 = command.Parameters["SomeOutVar1"].Value.ToString();
}
Simplest way to read json from a URL in java
I have found this to be the easiest way by far.
Use this method:
public static String getJSON(String url) {
HttpsURLConnection con = null;
try {
URL u = new URL(url);
con = (HttpsURLConnection) u.openConnection();
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
And use it like this:
String json = getJSON(url);
JSONObject obj;
try {
obj = new JSONObject(json);
JSONArray results_arr = obj.getJSONArray("results");
final int n = results_arr.length();
for (int i = 0; i < n; ++i) {
// get the place id of each object in JSON (Google Search API)
String place_id = results_arr.getJSONObject(i).getString("place_id");
}
}
android: how to change layout on button click?
I would add an android:onClick
to the layout and then change the layout in the activity.
So in the layout
<ImageView
(Other things like source etc.)
android:onClick="changelayout"
/>
Then in the activity add the following:
public void changelayout(View view){
setContentView(R.layout.second_layout);
}