android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>
I know this thread is old, but still answering it so that no-one else should spend sleepless nights.
I was refactoring an old project, whose layout files all contained hardcoded
attributes such as android:maxLength = 500
. So I decided to register it in my
res/dimen
file as <dimen name="max_length">500</dimen>
.
Finished refactoring almost 30 layout files with my res-value. Guess what? the next time I ran my project it started throwing the same InflateException
.
As a solution, needed to redo my all changes and keep all-those values as same as before.
TLDR;
step 1: All running good.
step 2: To boost my maintenance I replaced android:maxLength = 500
with <dimen name="max_length">500</dimen>
and android:maxLength = @dimen/max_length
, that's where it all went wrong(crashing with InflateException
).
step 3: All running bad
step 4: Re-do all my work by again replacing android:maxLength = @dimen/max_length
with android:maxLength = 500
.Everything got fixed.
step 5: All running good.
What does LayoutInflater in Android do?
When I first started Android programming, I was really confused by LayoutInflater
and findViewById
. Sometimes we used one and sometimes the other.
LayoutInflater
is used to create a new View
(or Layout
) object from one of your xml layouts.
findViewById
just gives you a reference to a view than has already been created. You might think that you haven't created any views yet, but whenever you call setContentView
in onCreate
, the activity's layout along with its subviews gets inflated (created) behind the scenes.
So if the view already exists, then use findViewById
. If not, then create it with a LayoutInflater
.
Example
Here is a mini project I made that shows both LayoutInflater
and findViewById
in action. With no special code, the layout looks like this.
The blue square is a custom layout inserted into the main layout with include
(see here for more). It was inflated automatically because it is part of the content view. As you can see, there is nothing special about the code.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Now let's inflate (create) another copy of our custom layout and add it in.
LayoutInflater inflater = getLayoutInflater();
View myLayout = inflater.inflate(R.layout.my_layout, mainLayout, false);
To inflate the new view layout, all I did was tell the inflater the name of my xml file (my_layout
), the parent layout that I want to add it to (mainLayout
), and that I don't actually want to add it yet (false
). (I could also set the parent to null
, but then the layout parameters of my custom layout's root view would be ignored.)
Here it is again in context.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// inflate the main layout for the activity
setContentView(R.layout.activity_main);
// get a reference to the already created main layout
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.activity_main_layout);
// inflate (create) another copy of our custom layout
LayoutInflater inflater = getLayoutInflater();
View myLayout = inflater.inflate(R.layout.my_layout, mainLayout, false);
// make changes to our custom layout and its subviews
myLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
TextView textView = (TextView) myLayout.findViewById(R.id.textView);
textView.setText("New Layout");
// add our custom layout to the main layout
mainLayout.addView(myLayout);
}
}
Notice how findViewById
is used only after a layout has already been inflated.
Supplemental Code
Here is the xml for the example above.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<!-- Here is the inserted layout -->
<include layout="@layout/my_layout"/>
</LinearLayout>
my_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/colorPrimary">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="5dp"
android:textColor="@android:color/white"
android:text="My Layout"/>
</RelativeLayout>
When do you need LayoutInflater
- The most common time most people use it is in a
RecyclerView
. (See these RecyclerView
examples for a list or a grid.) You have to inflate a new layout for every single visible item in the list or grid.
- You also can use a layout inflater if you have a complex layout that you want to add programmatically (like we did in our example). You could do it all in code, but it is much easier to define it in xml first and then just inflate it.
What does it mean to inflate a view from an xml file?
"Inflating" a view means taking the layout XML and parsing it to create the view and viewgroup objects from the elements and their attributes specified within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup. When you call setContentView(), it attaches the views it creates from reading the XML to the activity. You can also use LayoutInflater to add views to another ViewGroup, which can be a useful tool in a lot of circumstances.
How to inflate one view with a layout
You inflate an XML resource. See the LayoutInflater doc .
If your layout is in a mylayout.xml, you would do something like:
View view;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.mylayout, null);
RelativeLayout item = (RelativeLayout) view.findViewById(R.id.item);
How to add custom validation to an AngularJS form?
You can use Angular-Validator.
Example: using a function to validate a field
<input type = "text"
name = "firstName"
ng-model = "person.firstName"
validator = "myCustomValidationFunction(form.firstName)">
Then in your controller you would have something like
$scope.myCustomValidationFunction = function(firstName){
if ( firstName === "John") {
return true;
}
You can also do something like this:
<input type = "text"
name = "firstName"
ng-model = "person.firstName"
validator = "'!(field1 && field2 && field3)'"
invalid-message = "'This field is required'">
(where field1 field2, and field3 are scope variables. You might also want to check if the fields do not equal the empty string)
If the field does not pass the validator
then the field will be marked as invalid and the user will not be able to submit the form.
For more use cases and examples see: https://github.com/turinggroup/angular-validator
Disclaimer: I am the author of Angular-Validator
The data-toggle attributes in Twitter Bootstrap
For example, say you were creating a web application to list and display recipes. You might want your customers to be able to sort the list, display features of the recipes, and so on before they choose the recipe to open. In order to do this, you need to associate things like cooking time, primary ingredient, meal position, and so on right inside the list elements for the recipes.
<li><a href="recipe1.html">Borscht</a></li>
<li><a href="recipe2.html">Chocolate Mousse</a></li>
<li><a href="recipe3.html">Almond Radiccio Salad</a></li>
<li><a href="recipe4.html">Deviled Eggs</a></li>
In order to get that information into the page, you could do many different things. You could add comments to each LI element, you could add rel attributes to the list items, you could place all the recipes in separate folders based on time, meal, and ingredient (i.e. ). The solution that most developers took was to use class attributes to store information about the current element. This has several advantages:
- You can store multiple classes on an element
- The class names can be human readable
- It’s easy to access classes with JavaScript (className)
- The class is associated with the element it’s on
But there are some major drawbacks to this method:
- You have to remember what the classes do. If you forget or a new developer takes over the project, the classes might be removed or changed without realizing that that affects how the application runs.
- Classes are also used for styling with CSS, and you might duplicate CSS classes with data classes by mistake, ending up with strange styles on your live pages.
- It’s more difficult to add on multiple data elements. If you have multiple data elements, you need to access them in some way with your JavaScript, either by the name of the class or the position in the class list. But it’s easy to mess up.
All the other methods I suggested had these problems as well as others. But since it was the only way to quickly and easily include data, that’s what we did.
HTML5 Data Attributes to the Rescue
HTML5 added a new type of attribute to any element—the custom data element (data-*). These are custom (denoted by the *) attributes that you can add to your HTML elements to define any type of data you want. They consist of two parts:
Attribute Name
This is the name of the attribute. It must be at least one lowercase character and have the prefix data-. For example: data-main-ingredient, data-cooking-time, data-meal. This is the name of your data.
Attribute Vaule
Like any other HTML attribute, you include the data itself in quotes separated by an equal sign. This data can be any string that is valid on a web page. For example: data-main-ingredient="chocolate".
You can then apply these data attributes to any HTML element you want. For example, you could define the information in the example list above:
<li data-main-ingredient="beets" data-cooking-time="1 hour" data-meal="dinner"><a href="recipe1.html">Borscht</a></li>
<li data-main-ingredient="chocolate" data-cooking-time="30 minutes" data-meal="dessert"><a href="recipe2.html">Chocolate Mousse</a></li>
<li data-main-ingredient="radiccio" data-cooking-time="20 minutes" data-meal="dinner"><a href="recipe1.html">Almond Radiccio Salad</a></li>
<li data-main-ingredient="eggs" data-cooking-time="15 minutes" data-meal="appetizer"><a href="recipe1.html">Deviled Eggs</a></li>
Once you have that information in your HTML, you will be able to access it with JavaScript and manipulate the page based on that data.
How to make external HTTP requests with Node.js
node-http-proxy is a great solution as was suggested by @hross above. If you're not deadset on using node, we use NGINX to do the same thing. It works really well with node. We use it for example to process SSL requests before forwarding them to node. It can also handle cacheing and forwarding routes. Yay!
Sort Go map values by keys
If, like me, you find you want essentially the same sorting code in more than one place, or just want to keep the code complexity down, you can abstract away the sorting itself to a separate function, to which you pass the function that does the actual work you want (which would be different at each call site, of course).
Given a map with key type K
and value type V
, represented as <K>
and <V>
below, the common sort function might look something like this Go-code template (which Go version 1 does not support as-is):
/* Go apparently doesn't support/allow 'interface{}' as the value (or
/* key) of a map such that any arbitrary type can be substituted at
/* run time, so several of these nearly-identical functions might be
/* needed for different key/value type combinations. */
func sortedMap<K><T>(m map[<K>]<V>, f func(k <K>, v <V>)) {
var keys []<K>
for k, _ := range m {
keys = append(keys, k)
}
sort.Strings(keys) # or sort.Ints(keys), sort.Sort(...), etc., per <K>
for _, k := range keys {
v := m[k]
f(k, v)
}
}
Then call it with the input map and a function (taking (k <K>, v <V>)
as its input arguments) that is called over the map elements in sorted-key order.
So, a version of the code in the answer posted by Mingu might look like:
package main
import (
"fmt"
"sort"
)
func sortedMapIntString(m map[int]string, f func(k int, v string)) {
var keys []int
for k, _ := range m {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
f(k, m[k])
}
}
func main() {
// Create a map for processing
m := make(map[int]string)
m[1] = "a"
m[2] = "c"
m[0] = "b"
sortedMapIntString(m,
func(k int, v string) { fmt.Println("Key:", k, "Value:", v) })
}
The sortedMapIntString()
function can be re-used for any map[int]string
(assuming the same sort order is desired), keeping each use to just two lines of code.
Downsides include:
- It's harder to read for people unaccustomed to using functions as first-class
- It might be slower (I haven't done performance comparisons)
Other languages have various solutions:
- If the use of
<K>
and <V>
(to denote types for the key and value) looks a bit familiar, that code template is not terribly unlike C++ templates.
- Clojure and other languages support sorted maps as fundamental data types.
- While I don't know of any way Go makes
range
a first-class type such that it could be substituted with a custom ordered-range
(in place of range
in the original code), I think some other languages provide iterators that are powerful enough to accomplish the same thing.
What's the difference between a Python module and a Python package?
Any Python file is a module, its name being the file's base name without the .py
extension. A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional __init__.py
file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py
file.
The distinction between module and package seems to hold just at the file system level. When you import a module or a package, the corresponding object created by Python is always of type module
. Note, however, when you import a package, only variables/functions/classes in the __init__.py
file of that package are directly visible, not sub-packages or modules. As an example, consider the xml
package in the Python standard library: its xml
directory contains an __init__.py
file and four sub-directories; the sub-directory etree
contains an __init__.py
file and, among others, an ElementTree.py
file. See what happens when you try to interactively import package/modules:
>>> import xml
>>> type(xml)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>> import xml.etree
>>> type(xml.etree)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>> import xml.etree.ElementTree
>>> type(xml.etree.ElementTree)
<type 'module'>
>>> xml.etree.ElementTree.parse
<function parse at 0x00B135B0>
In Python there also are built-in modules, such as sys
, that are written in C, but I don't think you meant to consider those in your question.
Render HTML to an image
You could use PhantomJS, which is a headless webkit (the rendering engine in safari and (up until recently) chrome) driver. You can learn how to do screen capture of pages here. Hope that helps!
Android - How To Override the "Back" button so it doesn't Finish() my Activity?
Remove your key listener or return true
when you have KEY_BACK
.
You just need the following to catch the back key (Make sure not to call super in onBackPressed()
).
Also, if you plan on having a service run in the background, make sure to look at startForeground()
and make sure to have an ongoing notification or else Android will kill your service if it needs to free memory.
@Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
Android : How to read file in bytes?
here it's a simple:
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Add permission in manifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
How to create custom button in Android using XML Styles
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#ffffffff"/>
<size
android:width="@dimen/shape_circle_width"
android:height="@dimen/shape_circle_height"/>
</shape>
1.add this in your drawable
2.set as background to your button
sed whole word search and replace
in shell command:
echo "bar embarassment" | sed "s/\bbar\b/no bar/g"
or:
echo "bar embarassment" | sed "s/\<bar\>/no bar/g"
but if you are in vim, you can only use the later:
:% s/\<old\>/new/g
pandas groupby sort descending order
This kind of operation is covered under hierarchical indexing. Check out the examples here
When you groupby, you're making new indices. If you also pass a list through .agg(). you'll get multiple columns. I was trying to figure this out and found this thread via google.
It turns out if you pass a tuple corresponding to the exact column you want sorted on.
Try this:
# generate toy data
ex = pd.DataFrame(np.random.randint(1,10,size=(100,3)), columns=['features', 'AUC', 'recall'])
# pass a tuple corresponding to which specific col you want sorted. In this case, 'mean' or 'AUC' alone are not unique.
ex.groupby('features').agg(['mean','std']).sort_values(('AUC', 'mean'))
This will output a df sorted by the AUC-mean column only.
utf-8 special characters not displaying
The problem is because your file are not with the same encoding.
First run the following command in all your files:
file -i filename.*
In order to fix the problem you have to change all your files to uft-8. You can do it with the command iconv:
iconv -f fromcode -t tocode filename > newfilename
Example:
iconv -f iso-8859-1 -t utf-8 index.html > fixed/index.html
After this you can run file -i fixedx/index.html and you will see that your file is now in uft-8
Best C++ Code Formatter/Beautifier
AStyle can be customized in great detail for C++ and Java (and others too)
This is a source code formatting tool.
clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.
It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).
It can be configured with a variety of options listed here.
When using config files (named .clang-format
) styles can be per directory - the closest such file in parent directories shall be used for a particular file.
Styles can be inherited from a preset (say LLVM or Google) and can later override different options
It is used by Google and others and is production ready.
Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.
Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.
How do I format a Microsoft JSON date?
Just to add another approach here, the "ticks approach" that WCF takes is prone to problems with timezones if you're not extremely careful such as described here and in other places. So I'm now using the ISO 8601 format that both .NET & JavaScript duly support that includes timezone offsets. Below are the details:
In WCF/.NET:
Where CreationDate is a System.DateTime; ToString("o") is using .NET's Round-trip format specifier that generates an ISO 8601-compliant date string
new MyInfo {
CreationDate = r.CreationDate.ToString("o"),
};
In JavaScript
Just after retrieving the JSON I go fixup the dates to be JavaSript Date objects using the Date constructor which accepts an ISO 8601 date string...
$.getJSON(
"MyRestService.svc/myinfo",
function (data) {
$.each(data.myinfos, function (r) {
this.CreatedOn = new Date(this.CreationDate);
});
// Now each myinfo object in the myinfos collection has a CreatedOn field that is a real JavaScript date (with timezone intact).
alert(data.myinfos[0].CreationDate.toLocaleString());
}
)
Once you have a JavaScript date you can use all the convenient and reliable Date methods like toDateString, toLocaleString, etc.
Passing ArrayList from servlet to JSP
request.getAttribute("servletName")
method will return Object
that you need to cast to ArrayList
ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");
Convert base64 png data to javascript file objects
You can create a Blob
from your base64 data, and then read it asDataURL
:
var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];
var the_file = new Blob([window.atob(png)], {type: 'image/png', encoding: 'utf-8'});
var fr = new FileReader();
fr.onload = function ( oFREvent ) {
var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
v = atob(v);
var good_b64 = btoa(decodeURIComponent(escape(v)));
document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);
Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/
Alternatively, you can use .readAsText
, it works fine, and its more elegant.. but for some reason text does not sound right ;)
fr.onload = function ( oFREvent ) {
document.getElementById("uploadPreview").src = "data:image/png;base64,"
+ btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here
Full example: http://jsfiddle.net/tTYb8/3/
Hidden Columns in jqGrid
You can use the following code to hide a table column..
JQuery("tableName").hideCol("colName");
And you can use the following code to show it again.
JQuery("tableName").showCol("colName");
For your question, you can call the hideCol() code on the document.ready(), and you can bind the showCol() code on the dialog's edit/click event.
How to get the html of a div on another page with jQuery ajax?
If you are looking for content from different domain this will do the trick:
$.ajax({
url:'http://www.corsproxy.com/' +
'en.wikipedia.org/wiki/Briarcliff_Manor,_New_York',
type:'GET',
success: function(data){
$('#content').html($(data).find('#firstHeading').html());
}
});
Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger
Based on the stacktrace, an intuit class com.intuit.ipp.aggcat.util.SAML2AssertionGenerator needs a saml jar on the classpath.
A saml class org.opensaml.xml.XMLConfigurator needs on it's turn log4j, which is inside the WAR but cannot find it.
One explanation for this is that the class XMLConfigurator that needs log4j was found not inside the WAR but on a downstream classloader. could a saml jar be missing from the WAR?
The class XMLConfigurator that needs log4j cannot find it at the level of the classloader that loaded it, and the log4j version on the WAR is not visible on that particular classloader.
In order to troubleshoot this, a way is to add this before the oauth call:
System.out.println("all versions of log4j Logger: " + getClass().getClassLoader().getResources("org/apache/log4j/Logger.class") );
System.out.println("all versions of XMLConfigurator: " + getClass().getClassLoader().getResources("org/opensaml/xml/XMLConfigurator.class") );
System.out.println("all versions of XMLConfigurator visible from the classloader of the OAuthAuthorizer class: " + OAuthAuthorizer.class.getClassLoader().getResources("org/opensaml/xml/XMLConfigurator.class") );
System.out.println("all versions of log4j visible from the classloader of the OAuthAuthorizer class: " + OAuthAuthorizer.class.getClassloader().getResources("org/apache/log4j/Logger.class") );
Also if you are using Java 7, have a look at jHades, it's a tool I made to help troubleshooting these type of problems.
In order to see what is going on, could you post the results of the classpath queries above, for which container is this happening, tomcat, jetty? It would be better to put the full stacktrace with all the caused by's in pastebin, just in case.
CSS how to make scrollable list
Another solution would be as below where the list is placed under a drop-down button.
<button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
>Markets<span class="caret"></span></button>
<ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
{{ form.markets }}
</ul>
How to change default format at created_at and updated_at value laravel
Laravel 4.x and 5.0
To change the time in the database use:
http://laravel.com/docs/4.2/eloquent#timestamps
Providing A Custom Timestamp Format
If you wish to customize the format of your timestamps, you may override the getDateFormat method in your model:
class User extends Eloquent {
protected function getDateFormat()
{
return 'U';
}
}
Laravel 5.1+
https://laravel.com/docs/5.1/eloquent
If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:
class Flight extends Model
{
/**
* The storage format of the model's date columns.
*
* @var string
*/
protected $dateFormat = 'U';
}
How to load external webpage in WebView
try this
webviewlayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/help_webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none"
/>
In your Activity:
WebView webView;
setContentView(R.layout.webviewlayout);
webView = (WebView)findViewById(R.id.help_webview);
webView.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.google.com");
Update
Add webView.setWebViewClient(new WebViewController());
to your Activity.
WebViewController class:
public class WebViewController extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Associative arrays in Shell scripts
For Bash 3, there is a particular case that has a nice and simple solution:
If you don't want to handle a lot of variables, or keys are simply invalid variable identifiers, and your array is guaranteed to have less than 256 items, you can abuse function return values. This solution does not require any subshell as the value is readily available as a variable, nor any iteration so that performance screams. Also it's very readable, almost like the Bash 4 version.
Here's the most basic version:
hash_index() {
case $1 in
'foo') return 0;;
'bar') return 1;;
'baz') return 2;;
esac
}
hash_vals=("foo_val"
"bar_val"
"baz_val");
hash_index "foo"
echo ${hash_vals[$?]}
Remember, use single quotes in case
, else it's subject to globbing. Really useful for static/frozen hashes from the start, but one could write an index generator from a hash_keys=()
array.
Watch out, it defaults to the first one, so you may want to set aside zeroth element:
hash_index() {
case $1 in
'foo') return 1;;
'bar') return 2;;
'baz') return 3;;
esac
}
hash_vals=("", # sort of like returning null/nil for a non existent key
"foo_val"
"bar_val"
"baz_val");
hash_index "foo" || echo ${hash_vals[$?]} # It can't get more readable than this
Caveat: the length is now incorrect.
Alternatively, if you want to keep zero-based indexing, you can reserve another index value and guard against a non-existent key, but it's less readable:
hash_index() {
case $1 in
'foo') return 0;;
'bar') return 1;;
'baz') return 2;;
*) return 255;;
esac
}
hash_vals=("foo_val"
"bar_val"
"baz_val");
hash_index "foo"
[[ $? -ne 255 ]] && echo ${hash_vals[$?]}
Or, to keep the length correct, offset index by one:
hash_index() {
case $1 in
'foo') return 1;;
'bar') return 2;;
'baz') return 3;;
esac
}
hash_vals=("foo_val"
"bar_val"
"baz_val");
hash_index "foo" || echo ${hash_vals[$(($? - 1))]}
How to declare a global variable in php?
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
What's wrong with overridable method calls in constructors?
Here's an example which helps to understand this:
public class Main {
static abstract class A {
abstract void foo();
A() {
System.out.println("Constructing A");
foo();
}
}
static class C extends A {
C() {
System.out.println("Constructing C");
}
void foo() {
System.out.println("Using C");
}
}
public static void main(String[] args) {
C c = new C();
}
}
If you run this code, you get the following output:
Constructing A
Using C
Constructing C
You see? foo()
makes use of C before C's constructor has been run. If foo()
requires C to have a defined state (i.e. the constructor has finished), then it will encounter an undefined state in C and things might break. And since you can't know in A what the overwritten foo()
expects, you get a warning.
How to sort an STL vector?
std::sort(object.begin(), object.end(), pred());
where, pred()
is a function object defining the order on objects of myclass
. Alternatively, you can define myclass::operator<
.
For example, you can pass a lambda:
std::sort(object.begin(), object.end(),
[] (myclass const& a, myclass const& b) { return a.v < b.v; });
Or if you're stuck with C++03, the function object approach (v
is the member on which you want to sort):
struct pred {
bool operator()(myclass const & a, myclass const & b) const {
return a.v < b.v;
}
};
How to calculate distance from Wifi router using Signal Strength?
K = 32.44
FSPL = Ptx - CLtx + AGtx + AGrx - CLrx - Prx - FM
d = 10 ^ (( FSPL - K - 20 log10( f )) / 20 )
Here:
K
- constant (32.44, when f
in MHz and d
in km, change to -27.55 when f
in MHz and d
in m)
FSPL
- Free Space Path Loss
Ptx
- transmitter power, dBm ( up to 20 dBm (100mW) )
CLtx
, CLrx
- cable loss at transmitter and receiver, dB ( 0, if no cables )
AGtx
, AGrx
- antenna gain at transmitter and receiver, dBi
Prx
- receiver sensitivity, dBm ( down to -100 dBm (0.1pW) )
FM
- fade margin, dB ( more than 14 dB (normal) or more than 22 dB (good))
f
- signal frequency, MHz
d
- distance, m or km (depends on value of K)
Note: there is an error in formulas from TP-Link support site (mising ^
).
Substitute Prx
with received signal strength to get a distance from WiFi AP.
Example: Ptx = 16 dBm, AGtx = 2 dBi, AGrx = 0, Prx = -51 dBm (received signal strength), CLtx = 0, CLrx = 0, f = 2442 MHz (7'th 802.11bgn channel), FM = 22. Result: FSPL = 47 dB, d = 2.1865 m
Note: FM (fade margin) seems to be irrelevant here, but I'm leaving it because of the original formula.
You should take into acount walls, table http://www.liveport.com/wifi-signal-attenuation may help.
Example: (previous data) + one wooden wall ( 5 dB, from the table ). Result: FSPL = FSPL - 5 dB = 44 dB, d = 1.548 m
Also please note, that antena gain dosn't add power - it describes the shape of radiation pattern (donut in case of omnidirectional antena, zeppelin in case of directional antenna, etc).
None of this takes into account signal reflections (don't have an idea how to do this). Probably noise is also missing. So this math may be good only for rough distance estimation.
Find all elements with a certain attribute value in jquery
Although it doesn't precisely answer the question, I landed here when searching for a way to get the collection of elements (potentially different tag names) that simply had a given attribute name (without filtering by attribute value). I found that the following worked well for me:
$("*[attr-name]")
Hope that helps somebody who happens to land on this page looking for the same thing that I was :).
Update:
It appears that the asterisk is not required, i.e. based on some basic tests, the following seems to be equivalent to the above (thanks to Matt for pointing this out):
$("[attr-name]")
What is the difference between CMD and ENTRYPOINT in a Dockerfile?
Comments on EntryPoint function in code
// ENTRYPOINT /usr/sbin/nginx.
// Set the entrypoint (which defaults to sh -c) to /usr/sbin/nginx.
// Will accept the CMD as the arguments to /usr/sbin/nginx.
Another reference from documents
You can use the exec form of ENTRYPOINT to set fairly stable default commands and arguments and then use CMD to set additional defaults that are more likely to be changed.
Example:
FROM ubuntu:14.04.3
ENTRYPOINT ["/bin/ping"]
CMD ["localhost", "-c", "2"]
Build: sudo docker build -t ent_cmd .
CMD arguments are easy to override.
NO argument (sudo docker -it ent_cmd) : ping localhost
argument (sudo docker run -it ent_cmd google.com) : ping google.com
.
To override EntryPoint argument, you need to supply entrypoint
sudo docker run -it --entrypoint="/bin/bash" ent_cmdd
p.s:
In presence of EntryPoint, CMD will hold arguments to fed to EntryPoint.
In absense of EntryPoint, CMD will be the command which will be run.
Get and Set Screen Resolution
For retrieving the screen resolution, you're going to want to use the System.Windows.Forms.Screen
class. The Screen.AllScreens
property can be used to access a collection of all of the displays on the system, or you can use the Screen.PrimaryScreen
property to access the primary display.
The Screen
class has a property called Bounds
, which you can use to determine the resolution of the current instance of the class. For example, to determine the resolution of the current screen:
Rectangle resolution = Screen.PrimaryScreen.Bounds;
For changing the resolution, things get a little more complicated. This article (or this one) provides a detailed implementation and explanation. Hope this helps.
How can I use the MS JDBC driver with MS SQL Server 2008 Express?
You can try the following. Works fine in my case:
- Download the current jTDS JDBC Driver
- Put jtds-x.x.x.jar in your classpath.
- Copy ntlmauth.dll to windows/system32. Choose the dll based on your hardware x86,x64...
- The connection url is: 'jdbc:jtds:sqlserver://localhost:1433/YourDB' , you don't have to provide username and password.
Hope that helps.
git pull aborted with error filename too long
Solution1 - set global config, by running this command:
git config --system core.longpaths true
Solution2 - or you can edit directly your specific git config file like below:
YourRepoFolder -> .git -> config:
[core]
repositoryformatversion = 0
filemode = false
...
longpaths = true <-- (add this line under core section)
Solution3 - when cloning a new repository: here.
Clone() vs Copy constructor- which is recommended in java
Great sadness: neither Cloneable/clone nor a constructor are great solutions: I DON'T WANT TO KNOW THE IMPLEMENTING CLASS!!! (e.g. - I have a Map, which I want copied, using the same hidden MumbleMap implementation) I just want to make a copy, if doing so is supported. But, alas, Cloneable doesn't have the clone method on it, so there is nothing to which you can safely type-cast on which to invoke clone().
Whatever the best "copy object" library out there is, Oracle should make it a standard component of the next Java release (unless it already is, hidden somewhere).
Of course, if more of the library (e.g. - Collections) were immutable, this "copy" task would just go away. But then we would start designing Java programs with things like "class invariants" rather than the verdammt "bean" pattern (make a broken object and mutate until good [enough]).
Rename a table in MySQL
Without giving the database name the table is can't be renamed in my case, I followed the below command to rename the table.
RENAME TABLE current_db.tbl_name TO current_db.tbl_name;
Java Loop every minute
Use Thread.sleep(long millis)
.
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
One minute would be (60*1000) = 60000
milliseconds.
For example, this loop will print the current time once every 5 seconds:
try {
while (true) {
System.out.println(new Date());
Thread.sleep(5 * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
If your sleep period becomes too large for int
, explicitly compute in long
(e.g. 1000L
).
The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'
If both your client and service is installed on the same machine, and you are facing this problem with the correct (read: tried and tested elsewhere) client and service configurations, then this might be worth checking.
Check host entries in your host file
%windir%/system32/drivers/etc/hosts
Check to see if you are accessing your web service with a hostname, and that same hostname has been associated with an IP address in the hosts file mentioned above.
If yes, NTLM/Windows credentials will NOT be passed from the client to the service as any request for that hostname will be routed again at the machine level.
Try either of the following
-
Remove the host entry of that hostname from the hosts file
OR
-
If removing host entry is not possible, then try accessing your service with another hostname. You might also try with IP address instead of hostname
Edit:
Somehow the above situation is relevant on a load-balanced scenario.
However, if removing the host entries is not possible, then disabling loop back check on the machine will help.
Refer method 2 in the article https://support.microsoft.com/en-us/kb/896861
What does "var" mean in C#?
- As the name suggested, var is variable without any data type.
- If you don't know which type of data will be returned by any method, such cases are good for using var.
- var is Implicit type which means system will define the data type itself. The compiler will infer its type based on the value to the right of the "=" operator.
- int/string etc. are the explicit types as it is defined by you explicitly.
- Var can only be defined in a method as a local variable
- Multiple vars cannot be declared and initialized in a single statement. For example, var i=1, j=2; is invalid.
int i = 100;// explicitly typed
var j = 100; // implicitly typed
Differences between strong and weak in Objective-C
To understand Strong and Weak reference consider below example, suppose we have method named as displayLocalVariable.
-(void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(@"myView tag is = %ld", myView.tag);
}
In above method scope of myView variable is limited to displayLocalVariable method, once the method gets finished myView variable which is holding the UIView object will get deallocated from the memory.
Now what if we want to hold the myView variable throughout our view controller's life cycle. For this we can create the property named as usernameView which will have Strong reference to the variable myView(see @property(nonatomic,strong) UIView* usernameView;
and self.usernameView = myView;
in below code), as below,
@interface LoginViewController ()
@property(nonatomic,strong) UIView* usernameView;
@property(nonatomic,weak) UIView* dummyNameView;
- (void)displayLocalVariable;
@end
@implementation LoginViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
-(void)viewWillAppear:(BOOL)animated
{
[self displayLocalVariable];
}
- (void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(@"myView tag is = %ld", myView.tag);
self.usernameView = myView;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
Now in above code you can see myView has been assigned to self.usernameView and self.usernameView is having a strong reference(as we declared in interface using @property) to myView. Hence myView will not get deallocated from memory till self.usernameView is alive.
Now consider assigning myName to dummyNameView which is a Weak reference, self.dummyNameView = myView;
Unlike Strong reference Weak will hold the myView only till there is Strong reference to myView. See below code to understand Weak reference,
-(void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(@"myView tag is = %ld", myView.tag);
self.dummyNameView = myView;
}
In above code there is Weak reference to myView(i.e. self.dummyNameView is having Weak reference to myView) but there is no Strong reference to myView, hence self.dummyNameView will not be able to hold the myView value.
Now again consider the below code,
-(void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(@"myView tag is = %ld", myView.tag);
self.usernameView = myView;
self.dummyNameView = myView;
}
In above code self.usernameView has a Strong reference to myView, hence self.dummyNameView will now have a value of myView even after method ends since myView has a Strong reference associated with it.
Now whenever we make a Strong reference to a variable it's retain count get increased by one and the variable will not get deallocated till it's retain count reaches to 0.
Hope this helps.
How do I list / export private keys from a keystore?
First of all, be careful! All of your security depends on the… er… privacy of your private keys. Keytool doesn't have key export built in to avoid accidental disclosure of this sensitive material, so you might want to consider some extra safeguards that could be put in place to protect your exported keys.
Here is some simple code that gives you unencrypted PKCS #8 PrivateKeyInfo that can be used by OpenSSL (see the -nocrypt
option of its pkcs8 utility):
KeyStore keys = ...
char[] password = ...
Enumeration<String> aliases = keys.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (!keys.isKeyEntry(alias))
continue;
Key key = keys.getKey(alias, password);
if ((key instanceof PrivateKey) && "PKCS#8".equals(key.getFormat())) {
/* Most PrivateKeys use this format, but check for safety. */
try (FileOutputStream os = new FileOutputStream(alias + ".key")) {
os.write(key.getEncoded());
os.flush();
}
}
}
If you need other formats, you can use a KeyFactory to get a transparent key specification for different types of keys. Then you can get, for example, the private exponent of an RSA private key and output it in your desired format. That would make a good topic for a follow-up question.
Unsupported method: BaseConfig.getApplicationIdSuffix()
First, open your application module build.gradle file.
Check the classpath according to your project dependency. If not change the version of this classpath.
from:
classpath 'com.android.tools.build:gradle:1.0.0'
To:
classpath 'com.android.tools.build:gradle:2.3.2'
or higher version according to your gradle of android studio.
If its still problem, then change buildToolsVersion:
From:
buildToolsVersion '21.0.0'
To:
buildToolsVersion '25.0.0'
then hit 'Try again' and gradle will automatically sync.
This will solve it.
How to add a new line of text to an existing file in Java?
Starting from Java 7:
Define a path and the String containing the line separator at the beginning:
Path p = Paths.get("C:\\Users\\first.last\\test.txt");
String s = System.lineSeparator() + "New Line!";
and then you can use one of the following approaches:
Using Files.write
(small files):
try {
Files.write(p, s.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
System.err.println(e);
}
Using Files.newBufferedWriter
(text files):
try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) {
writer.write(s);
} catch (IOException ioe) {
System.err.format("IOException: %s%n", ioe);
}
Using Files.newOutputStream
(interoperable with java.io
APIs):
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) {
out.write(s.getBytes());
} catch (IOException e) {
System.err.println(e);
}
Using Files.newByteChannel
(random access files):
try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) {
sbc.write(ByteBuffer.wrap(s.getBytes()));
} catch (IOException e) {
System.err.println(e);
}
Using FileChannel.open
(random access files):
try (FileChannel sbc = FileChannel.open(p, StandardOpenOption.APPEND)) {
sbc.write(ByteBuffer.wrap(s.getBytes()));
} catch (IOException e) {
System.err.println(e);
}
Details about these methods can be found in the Oracle's tutorial.
Inserting HTML elements with JavaScript
If you want to insert HTML code inside existing page's tag use Jnerator. This tool was created specially for this goal.
Instead of writing next code
var htmlCode = '<ul class=\'menu-countries\'><li
class=\'item\'><img src=\'au.png\'></img><span>Australia </span></li><li
class=\'item\'><img src=\'br.png\'> </img><span>Brazil</span></li><li
class=\'item\'> <img src=\'ca.png\'></img><span>Canada</span></li></ul>';
var element = document.getElementById('myTag');
element.innerHTML = htmlCode;
You can write more understandable structure
var jtag = $j.ul({
class: 'menu-countries',
child: [
$j.li({ class: 'item', child: [
$j.img({ src: 'au.png' }),
$j.span({ child: 'Australia' })
]}),
$j.li({ class: 'item', child: [
$j.img({ src: 'br.png' }),
$j.span({ child: 'Brazil' })
]}),
$j.li({ class: 'item', child: [
$j.img({ src: 'ca.png' }),
$j.span({ child: 'Canada' })
]})
]
});
var htmlCode = jtag.html();
var element = document.getElementById('myTag');
element.innerHTML = htmlCode;
How to Change Font Size in drawString Java
I've an image located at here, Using below code. I am able to contgrol any things on the text that i wanted to write (Eg,signature,Transparent Water mark, Text with differnt Font and size).
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
public class ImagingTest {
public static void main(String[] args) throws IOException {
String url = "http://images.all-free-download.com/images/graphiclarge/bay_beach_coast_coastline_landscape_nature_nobody_601234.jpg";
String text = "I am appending This text!";
byte[] b = mergeImageAndText(url, text, new Point(100, 100));
FileOutputStream fos = new FileOutputStream("so2.png");
fos.write(b);
fos.close();
}
public static byte[] mergeImageAndText(String imageFilePath,
String text, Point textPosition) throws IOException {
BufferedImage im = ImageIO.read(new URL(imageFilePath));
Graphics2D g2 = im.createGraphics();
Font currentFont = g2.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g2.setFont(newFont);
Map<TextAttribute, Object> attributes = new HashMap<>();
attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 2.8));
newFont = Font.getFont(attributes);
g2.setFont(newFont);
g2.drawString(text, textPosition.x, textPosition.y);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(im, "png", baos);
return baos.toByteArray();
}
}
Reading CSV files using C#
To complete the previous answers, one may need a collection of objects from his CSV File, either parsed by the TextFieldParser
or the string.Split
method, and then each line converted to an object via Reflection. You obviously first need to define a class that matches the lines of the CSV file.
I used the simple CSV Serializer from Michael Kropat found here: Generic class to CSV (all properties)
and reused his methods to get the fields and properties of the wished class.
I deserialize my CSV file with the following method:
public static IEnumerable<T> ReadCsvFileTextFieldParser<T>(string fileFullPath, string delimiter = ";") where T : new()
{
if (!File.Exists(fileFullPath))
{
return null;
}
var list = new List<T>();
var csvFields = GetAllFieldOfClass<T>();
var fieldDict = new Dictionary<int, MemberInfo>();
using (TextFieldParser parser = new TextFieldParser(fileFullPath))
{
parser.SetDelimiters(delimiter);
bool headerParsed = false;
while (!parser.EndOfData)
{
//Processing row
string[] rowFields = parser.ReadFields();
if (!headerParsed)
{
for (int i = 0; i < rowFields.Length; i++)
{
// First row shall be the header!
var csvField = csvFields.Where(f => f.Name == rowFields[i]).FirstOrDefault();
if (csvField != null)
{
fieldDict.Add(i, csvField);
}
}
headerParsed = true;
}
else
{
T newObj = new T();
for (int i = 0; i < rowFields.Length; i++)
{
var csvFied = fieldDict[i];
var record = rowFields[i];
if (csvFied is FieldInfo)
{
((FieldInfo)csvFied).SetValue(newObj, record);
}
else if (csvFied is PropertyInfo)
{
var pi = (PropertyInfo)csvFied;
pi.SetValue(newObj, Convert.ChangeType(record, pi.PropertyType), null);
}
else
{
throw new Exception("Unhandled case.");
}
}
if (newObj != null)
{
list.Add(newObj);
}
}
}
}
return list;
}
public static IEnumerable<MemberInfo> GetAllFieldOfClass<T>()
{
return
from mi in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
where new[] { MemberTypes.Field, MemberTypes.Property }.Contains(mi.MemberType)
let orderAttr = (ColumnOrderAttribute)Attribute.GetCustomAttribute(mi, typeof(ColumnOrderAttribute))
orderby orderAttr == null ? int.MaxValue : orderAttr.Order, mi.Name
select mi;
}
Check if application is installed - Android
If you want to try it without the try catch block, can use the following method,
Create a intent and set the package of the app which you want to verify
val intent = Intent(Intent.ACTION_VIEW)
intent.data = uri
intent.setPackage("com.example.packageofapp")
and the call the following method to check if the app is installed
fun isInstalled(intent:Intent) :Boolean{
val list = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
return list.isNotEmpty()
}
AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation
<script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script type="text/javascript">
function controller($scope) {
$scope.data = {
show: true,
hide: false
};
}
</script>
<div ng-controller="controller">
<div ng-show="data.show"> If true the show otherwise hide. </div>
<div ng-hide="!(data.hide)"> If true the show otherwise hide.</div>
</div>
jQuery load first 3 elements, click "load more" to display next 5 elements
The expression $(document).ready(function() deprecated in jQuery3.
See working fiddle with jQuery 3 here
Take into account I didn't include the showless button.
Here's the code:
JS
$(function () {
x=3;
$('#myList li').slice(0, 3).show();
$('#loadMore').on('click', function (e) {
e.preventDefault();
x = x+5;
$('#myList li').slice(0, x).slideDown();
});
});
CSS
#myList li{display:none;
}
#loadMore {
color:green;
cursor:pointer;
}
#loadMore:hover {
color:black;
}
How to extract numbers from a string and get an array of ints?
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(myString);
while (m.find()) {
int n = Integer.parseInt(m.group());
// append n to list
}
// convert list to array, etc
You can actually replace [0-9] with \d, but that involves double backslash escaping, which makes it harder to read.
SQL Server: Multiple table joins with a WHERE clause
Try this working fine....
SELECT computer.NAME, application.NAME,software.Version FROM computer LEFT JOIN software_computer ON(computer.ID = software_computer.ComputerID)
LEFT JOIN software ON(software_computer.SoftwareID = Software.ID) LEFT JOIN application ON(application.ID = software.ApplicationID)
where computer.id = 1 group by application.NAME UNION SELECT computer.NAME, application.NAME,
NULL as Version FROM computer, application WHERE application.ID not in ( SELECT s.applicationId FROM software_computer sc LEFT JOIN software s
on s.ID = sc.SoftwareId WHERE sc.ComputerId = 1 )
AND computer.id = 1
How do I use Ruby for shell scripting?
The above answer are interesting and very helpful when using Ruby as shell script. For me, I does not use Ruby as my daily language and I prefer to use ruby as flow control only and still use bash to do the tasks.
Some helper function can be used for testing execution result
#!/usr/bin/env ruby
module ShellHelper
def test(command)
`#{command} 2> /dev/null`
$?.success?
end
def execute(command, raise_on_error = true)
result = `#{command}`
raise "execute command failed\n" if (not $?.success?) and raise_on_error
return $?.success?
end
def print_exit(message)
print "#{message}\n"
exit
end
module_function :execute, :print_exit, :test
end
With helper, the ruby script could be bash alike:
#!/usr/bin/env ruby
require './shell_helper'
include ShellHelper
print_exit "config already exists" if test "ls config"
things.each do |thing|
next if not test "ls #{thing}/config"
execute "cp -fr #{thing}/config_template config/#{thing}"
end
scp (secure copy) to ec2 instance without password
In your case, the user root
won't have any issues. But in certain cases where you're required to login under SSH as a different user, make sure the directory you're scp
-ing has adequate permissions for the user you're SSH-ing.
Loading basic HTML in Node.js
try this one:
var http = require('http');
var fs = require('fs');
var PORT = 8080;
http.createServer((req, res) => {
fs.readFile('./' + req.url, (err, data) => {
if (!err) {
var dotoffset = req.url.lastIndexOf('.');
var mimetype = dotoffset == -1 ? 'text/plaint' : {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.jpg': 'image/jpeg',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.gif': 'image/gif'
}[ req.url.substr(dotoffset) ];
res.setHeader('Content-Type', mimetype);
res.end(data);
console.log(req.url, mimetype);
} else {
console.log('File not fount: ' + req.url);
res.writeHead(404, "Not Found");
res.end();
}
});
}).listen(PORT);
With this, you can include js, css source-codes when linking them and you can load icons, imgs, gifs. And if you want, you can add more if you need.
How to get hostname from IP (Linux)?
Another simple way I found for using in LAN is
ssh [username@ip] uname -n
If you need to login command line will be
sshpass -p "[password]" ssh [username@ip] uname -n
Running two projects at once in Visual Studio
Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.
This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).
How to find my Subversion server version number?
If you use VisualSVN Server, you can find out the version number by several different means.
Use VisualSVN Server Manager
Follow these steps to find out the version via the management console:
- Start the VisualSVN Server Manager console.
- See the Version at the bottom-right corner of the dashboard.
If you click Version you will also see the versions of the components.
Check the README.txt file
Follow these steps to find out the version from the readme.txt file:
- Start notepad.exe.
- Open the %VISUALSVN_SERVER%README.txt file. The first line shows the version number.
Is there a way to break a list into columns?
This answer doesn't necessarily scale but only requires minor adjustments as the list grows. Semantically it might seem a little counter-intuitive since it is two lists, but aside from that it'll look the way you want in any browser ever made.
_x000D_
_x000D_
ul {_x000D_
float: left;_x000D_
}_x000D_
_x000D_
ul > li {_x000D_
width: 6em;_x000D_
}
_x000D_
<!-- Column 1 -->_x000D_
<ul>_x000D_
<li>Item 1</li>_x000D_
<li>Item 2</li>_x000D_
<li>Item 3</li>_x000D_
</ul>_x000D_
<!-- Column 2 -->_x000D_
<ul>_x000D_
<li>Item 4</li>_x000D_
<li>Item 5</li>_x000D_
<li>Item 6</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_
What key in windows registry disables IE connection parameter "Automatically Detect Settings"?
For anyone looking to untick the 'Automatically Detect Settings' box without overwriting the other settings contained in the registry entry, you can use vbscript at logon.
On Error Resume Next
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
sKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"
sValueName = "DefaultConnectionSettings"
' Get registry value where each byte is a different setting.
oReg.GetBinaryValue &H80000001, sKeyPath, sValueName, bValue
' Check byte to see if detect is currently on.
If (bValue(8) And 8) = 8 Then
' Turn off detect and write back settings value.
bValue(8) = bValue(8) And Not 8
oReg.SetBinaryValue &H80000001, sKeyPath, sValueName, bValue
End If
Set oReg = Nothing
Formatting a number with exactly two decimals in JavaScript
With these examples you will still get an error when trying to round the number 1.005 the solution is to either use a library like Math.js or this function:
function round(value: number, decimals: number) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
How to check if curl is enabled or disabled
Its always better to go for a generic reusable function in your project which returns whether the extension loaded. You can use the following function to check -
function isExtensionLoaded($extension_name){
return extension_loaded($extension_name);
}
Usage
echo isExtensionLoaded('curl');
echo isExtensionLoaded('gd');
How can I create an editable dropdownlist in HTML?
The <select>
tag only allows the use of predefined entries. The typical solution to your problem is to have one entry labeled 'Other' and a disabled edit field (<input type="text"
). Add some JavaScript to enable the edit field only when 'Other' is selected.
It may be possible to somehow create a dropdown that allows direct editing, but IMO that is not worth the effort. If it was, Amazon, Google or Microsoft would be doing it ;-) Just get the job done with the least complicated solution. It as faster (your boss may like that) and usually easier to maintain (you may like that).
How can I pass a username/password in the header to a SOAP WCF Service
I added customBinding to the web.config.
<configuration>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="CustomSoapBinding">
<security includeTimestamp="false"
authenticationMode="UserNameOverTransport"
defaultAlgorithmSuite="Basic256"
requireDerivedKeys="false"
messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10">
</security>
<textMessageEncoding messageVersion="Soap11"></textMessageEncoding>
<httpsTransport maxReceivedMessageSize="2000000000"/>
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="https://test.com:443/services/testService"
binding="customBinding"
bindingConfiguration="CustomSoapBinding"
contract="testService.test"
name="test" />
</client>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
After adding customBinding, I can pass username and password to client service like as follows:
service.ClientCridentials.UserName.UserName = "testUser";
service.ClientCridentials.UserName.Password = "testPass";
In this way you can pass username, password in the header to a SOAP WCF Service.
Update Fragment from ViewPager
I faced problem some times so that in this case always avoid FragmentPagerAdapter and use FragmentStatePagerAdapter.
It work for me. I hope it will work for you also.
Accessing value inside nested dictionaries
My implementation:
def get_nested(data, *args):
if args and data:
element = args[0]
if element:
value = data.get(element)
return value if len(args) == 1 else get_nested(value, *args[1:])
Example usage:
>>> dct={"foo":{"bar":{"one":1, "two":2}, "misc":[1,2,3]}, "foo2":123}
>>> get_nested(dct, "foo", "bar", "one")
1
>>> get_nested(dct, "foo", "bar", "two")
2
>>> get_nested(dct, "foo", "misc")
[1, 2, 3]
>>> get_nested(dct, "foo", "missing")
>>>
There are no exceptions raised in case a key is missing, None value is returned in that case.
How to find the type of an object in Go?
I would stay away from the reflect. package. Instead use %T
package main
import (
"fmt"
)
func main() {
b := true
s := ""
n := 1
f := 1.0
a := []string{"foo", "bar", "baz"}
fmt.Printf("%T\n", b)
fmt.Printf("%T\n", s)
fmt.Printf("%T\n", n)
fmt.Printf("%T\n", f)
fmt.Printf("%T\n", a)
}
Redis command to get all available keys?
-->Get all keys from redis-cli
-redis 127.0.0.1:6379> keys *
-->Get list of patterns
-redis 127.0.0.1:6379> keys d??
This will produce keys which start by 'd' with three characters.
-redis 127.0.0.1:6379> keys *t*
This wil get keys with matches 't' character in key
-->Count keys from command line by
-redis-cli keys * |wc -l
-->Or you can use dbsize
-redis-cli dbsize
Redirect from an HTML page
You should use JavaScript. Place the following code in your head tags:
<script type="text/javascript">
window.location.assign("http://www.example.com")
</script>
Why doesn't CSS ellipsis work in table cell?
Leave your tables as they are. Just wrap the content inside the TD's with a span that has the truncation CSS applied.
/* CSS */
.truncate {
width: 50px; /*your fixed width */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: block; /* this fixes your issue */
}
<!-- HTML -->
<table>
<tbody>
<tr>
<td>
<span class="truncate">
Table data to be truncated if it's too long.
</span>
</td>
</tr>
</tbody>
</table>
How to clone all remote branches in Git?
A little late to the party, but I think this does the trick:
mkdir YourRepo
cd YourRepo
git init --bare .git # create a bare repo
git remote add origin REMOTE_URL # add a remote
git fetch origin refs/heads/*:refs/heads/* # fetch heads
git fetch origin refs/tags/*:refs/tags/* # fetch tags
git init # reinit work tree
git checkout master # checkout a branch
If this does something undesirable, I'd love to know. However, so far, this works for me.
Python virtualenv questions
Normally virtualenv
creates environments in the current directory. Unless you're intending to create virtual environments in C:\Windows\system32
for some reason, I would use a different directory for environments.
You shouldn't need to mess with paths: use the activate
script (in <env>\Scripts
) to ensure that the Python executable and path are environment-specific. Once you've done this, the command prompt changes to indicate the environment. You can then just invoke easy_install and whatever you install this way will be installed into this environment. Use deactivate
to set everything back to how it was before activation.
Example:
c:\Temp>virtualenv myenv
New python executable in myenv\Scripts\python.exe
Installing setuptools..................done.
c:\Temp>myenv\Scripts\activate
(myenv) C:\Temp>deactivate
C:\Temp>
Notice how I didn't need to specify a path for deactivate
- activate
does that for you, so that when activated "Python" will run the Python in the virtualenv, not your system Python. (Try it - do an import sys; sys.prefix
and it should print the root of your environment.)
You can just activate a new environment to switch between environments/projects, but you'll need to specify the whole path for activate
so it knows which environment to activate. You shouldn't ever need to mess with PATH or PYTHONPATH explicitly.
If you use Windows Powershell then you can take advantage of a wrapper. On Linux, the virtualenvwrapper
(the link points to a port of this to Powershell) makes life with virtualenv
even easier.
Update: Not incorrect, exactly, but perhaps not quite in the spirit of virtualenv
. You could take a different tack: for example, if you install Django and anything else you need for your site in your virtualenv, then you could work in your project directory (where you're developing your site) with the virtualenv activated. Because it was activated, your Python would find Django and anything else you'd easy_installed into the virtual environment: and because you're working in your project directory, your project files would be visible to Python, too.
Further update: You should be able to use pip
, distribute
instead of setuptools
, and just plain python setup.py install
with virtualenv
. Just ensure you've activated an environment before installing something into it.
java how to use classes in other package?
Given your example, you need to add the following import in your main.main
class:
import second.second;
Some bonus advice, make sure you titlecase your class names as that is a Java standard. So your example Main class will have the structure:
package main; //lowercase package names
public class Main //titlecase class names
{
//Main class content
}
How can I know which radio button is selected via jQuery?
How about this?
Using change and get the value of radio type is checked...
_x000D_
_x000D_
$('#my-radio-form').on('change', function() {_x000D_
console.log($('[type="radio"]:checked').val());_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<form id="my-radio-form">_x000D_
<input type="radio" name="input-radio" value="a" />a_x000D_
<input type="radio" name="input-radio" value="b" />b_x000D_
<input type="radio" name="input-radio" value="c" />c_x000D_
<input type="radio" name="input-radio" value="d" />d_x000D_
</form>
_x000D_
_x000D_
_x000D_
Easiest way to copy a single file from host to Vagrant guest?
Vagrant provides a way to execute a command over ssh instead of logging in, so for Linux host and guest you can use:
cat ~/file_on_host.txt | vagrant ssh -c 'cat - > ~/file_on_guest.txt'
vagrant ssh -c 'cat ~/file_on_guest.txt' > ~/file_on_host.txt
No need for plugins or guest reloads. Just make sure to provide vagrant box ID to 'vagrant ssh' if you are not in the same dir as the Vagrantfile. Tested on Vagrant v1.8.1.
How set maximum date in datepicker dialog in android?
You can create Custom date picker, that is work for all api levels.
public class CustomDatePickerDialog extends DatePickerDialog {
int maxYear;
int maxMonth;
int maxDay;
public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
super(context, callBack, year, monthOfYear, dayOfMonth);
}
public void setMaxDate(long maxDate) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getDatePicker().setMaxDate(System.currentTimeMillis());
} else {
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(maxDate);
maxYear = c.get(Calendar.YEAR);
maxMonth = c.get(Calendar.MONTH);
maxDay = c.get(Calendar.DAY_OF_MONTH);
}
}
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
super.onDateChanged(view, year, monthOfYear, dayOfMonth);
} else {
if (year > maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (monthOfYear > maxMonth && year == maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
view.updateDate(maxYear, maxMonth, maxDay);
}
}
set max date
final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(getActivity(),
myDateListener, year, month, day);
pickerDialog.setMaxDate(System.currentTimeMillis());
pickerDialog.show();
Case-insensitive search in Rails model
Similar to Andrews which is #1:
Something that worked for me is:
name = "Blue Jeans"
Product.find_by("lower(name) = ?", name.downcase)
This eliminates the need to do a #where
and #first
in the same query. Hope this helps!
How to specify the JDK version in android studio?
For new Android Studio versions, go to C:\Program Files\Android\Android Studio\jre\bin(or to location of Android Studio installed files) and open command window at this location and type in following command in command prompt:-
java -version
How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>
I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!
Thus, the way I fixed it was:
apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -
Then running a new "apt-get update" worked flawlessly!
What is web.xml file and what are all things can I do with it?
What is web.xml file and what all things can I do with it ?
The /WEB-INF/web.xml
file is the Web Application Deployment Descriptor of your application. This file is an XML document that defines everything about your application that a server needs to know (except the context path, which is assigned by the Application Deployer and Administrator when the application is deployed): servlets and other components like filters or listeners, initialization parameters, container-managed security constraints, resources, welcome pages, etc.
Note that reference you mentioned is pretty old (Java EE 1.4), there have been few changes in Java EE 5 and even more in Java EE 6 (which makes the web.xml
"optional" and introduces Web Fragments).
Is there any configuration parameter which should be avoided like plague?
No.
Any parameters related to performance or memory usage?
No, such things are not configured at the application level but at the container level.
Security related risk due to common mis-configuration ?
Well, if you want to use container-managed security constraints and fail at configuring them properly, resources won't obviously be properly protected. Apart from that, the biggest security risks come from the code you'll deploy IMO.
C# Change A Button's Background Color
// WPF
// Defined Color
button1.Background = Brushes.Green;
// Color from RGB
button2.Background = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));
Generating unique random numbers (integers) between 0 and 'x'
Use the basic Math
methods:
Example:
//Example, including customisable intervals [lower_bound, upper_bound)
var limit = 10,
amount = 3,
lower_bound = 1,
upper_bound = 10,
unique_random_numbers = [];
if (amount > limit) limit = amount; //Infinite loop if you want more unique
//Natural numbers than exist in a
// given range
while (unique_random_numbers.length < limit) {
var random_number = Math.floor(Math.random()*(upper_bound - lower_bound) + lower_bound);
if (unique_random_numbers.indexOf(random_number) == -1) {
// Yay! new random number
unique_random_numbers.push( random_number );
}
}
// unique_random_numbers is an array containing 3 unique numbers in the given range
File to import not found or unreadable: compass
If you're like me and came here looking for a way to make sass --watch work with compass, the answer is to use Compass' version of watch, simply:
compass watch
If you're on a Mac and don't yet have the gem installed, you might run into errors when you try to install the Compass gem, due to permission problems that arise on OSX versions later than 10.11. Install ruby with Homebrew to get around this. See this answer for how to do that.
Alternatively you could just use CodeKit, but if you're stubborn like me and want to use Sublime Text and command line, this is the route to go.
Waiting for Target Device to Come Online
For Linux users using KVM and facing this problem try setting the Graphics option on the Android Virtual Device to Software
instead of Automatic
or Hardware
. As previously mentioned in this answer.
I can confirm that the method works for Arch Linux, Ubuntu 16.04, as well as windows with or without a proprietary graphics card using Android Studio version 2.3.1+
What is /dev/null 2>&1?
As described by the others, writing to /dev/null eliminates the output of a program. Usually cron sends an email for every output from the process started with a cronjob. So by writing the output to /dev/null you prevent being spammed if you have specified your adress in cron.
Difference between uint32 and uint32_t
uint32_t
is defined in the standard, in
18.4.1 Header <cstdint>
synopsis [cstdint.syn]
namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}
uint32
is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32
) for ease of use.
Chrome not rendering SVG referenced via <img> tag
Had the same problem. If server is configured correctly and .htacces is not the answer, might want to look the svg source you are embedding. Mine were created with text editor, rendered well on Chrome&Safari inside html5 code, once embedded, nothing was visible.
Added correct version, dimensions etc to the svg code and works like a charm.
Also, all styles inline.
Ie
<svg version="1.1" baseProfile="full" width="24" height="24" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" rx="2" ry="2" width="24" height="24" style="fill:#fbc800;width:24px;height:24px;" />
</svg>
SQL - Create view from multiple tables
Union is not what you want. You want to use joins to create single rows. It's a little unclear what constitutes a unique row in your tables and how they really relate to each other and it's also unclear if one table will have rows for every country in every year. But I think this will work:
CREATE VIEW V AS (
SELECT i.country,i.year,p.pop,f.food,i.income FROM
INCOME i
LEFT JOIN
POP p
ON
i.country=p.country
LEFT JOIN
Food f
ON
i.country=f.country
WHERE
i.year=p.year
AND
i.year=f.year
);
The left (outer) join will return rows from the first table even if there are no matches in the second. I've written this assuming you would have a row for every country for every year in the income table. If you don't things get a bit hairy as MySQL does not have built in support for FULL OUTER JOINs last I checked. There are ways to simulate it, and they would involve unions. This article goes into some depth on the subject: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/
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.
Non-resolvable parent POM using Maven 3.0.3 and relativePath notation
I had the same problem. My project layout looked like
\---super
\---thirdparty
+---mod1-root
| +---mod1-linux32
| \---mod1-win32
\---mod2-root
+---mod2-linux32
\---mod2-win32
In my case, I had a mistake in my pom.xmls at the modX-root-level. I had copied the mod1-root tree and named it mod2-root. I incorrectly thought I had updated all the pom.xmls appropriately; but in fact, mod2-root/pom.xml had the same group and artifact ids as mod1-root/pom.xml. After correcting mod2-root's pom.xml to have mod2-root specific maven coordinates my issue was resolved.
Non-numeric Argument to Binary Operator Error in R
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP
I use the AdWords API, and sometimes I have the same problem.
My solution is to add
ini_set('default_socket_timeout', 900);
on the file
vendor\googleads\googleads-php-lib\src\Google\AdsApi\AdsSoapClient.php line 65
and in the
vendor\googleads-php-lib\src\Google\AdsApi\Adwords\Reporting\v201702\ReportDownloader.php line 126
ini_set('default_socket_timeout', 900);
$requestOptions['stream_context']['http']['timeout'] = "900";
Google package overwrite the default php.ini parameter.
Sometimes, the page could connect to 'https://adwords.google.com/ap
i/adwords/mcm/v201702/ManagedCustomerService?wsdl and sometimes no.
If the page connects once, The WSDL cache will contain the same page, and the program will be ok until the code refreshes the cache...
How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?
I have a simple example here to display date and time with Millisecond......
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class MyClass{
public static void main(String[]args){
LocalDateTime myObj = LocalDateTime.now();
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS);
String forDate = myObj.format(myFormat);
System.out.println("The Date and Time are: " + forDate);
}
}
css3 text-shadow in IE9
The answer of crdunst is pretty neat and the best looking answer I've found but there's no explanation on how to use and the code is bigger than needed.
The only code you need:
#element {
background-color: #cacbcf;
text-shadow: 2px 2px 4px rgba(0,0,0, 0.5);
filter: chroma(color=#cacbcf) progid:DXImageTransform.Microsoft.dropshadow(color=#60000000, offX=2, offY=2);
}
First you MUST specify a background-color
- if your element should be transparent just copy the background-color of the parent or let it inherit. The color at the chroma-filter must match the background-color to fix those artifacts around the text (but here you must copy the color, you can't write inherit
). Note that I haven't shortened the dropshadow-filter - it works but the shadows are then cut to the element dimensions (noticeable with big shadows; try to set the offsets to atleast 4).
TIP: If you want to use colors with transparency (alpha-channel) write in a #AARRGGBB notation, where AA stands for a hexadezimal value of the opacity - from 01 to FE, because FF and ironically also 00 means no transparency and is therefore useless.. ^^ Just go a little lower than in the rgba notation because the shadows aren't soft and the same alpha value would appear darker then. ;)
A nice snippet to convert the alpha value for IE (JavaScript, just paste into the console):
var number = 0.5; //alpha value from the rgba() notation
("0"+(Math.round(0.75 * number * 255).toString(16))).slice(-2);
ISSUES: The text/font behaves like an image after the shadow is applied; it gets pixelated and blurry after you zoom in... But that's IE's issue, not mine.
Live demo of the shadow here: http://jsfiddle.net/12khvfru/2/
Automatically creating directories with file output
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
jQuery - Detect value change on hidden input field
Although this thread is 3 years old, here is my solution:
$(function ()
{
keep_fields_uptodate();
});
function keep_fields_uptodate()
{
// Keep all fields up to date!
var $inputDate = $("input[type='date']");
$inputDate.blur(function(event)
{
$("input").trigger("change");
});
}
How do I tell a Python script to use a particular version
While the OP may be working on a nix platform this answer could help non-nix platforms. I have not experienced the shebang approach work in Microsoft Windows.
Rephrased: The shebang line answers your question of "within my script" but I believe only for Unix-like platforms. Even though it is the Unix shell, outside the script, that actually interprets the shebang line to determine which version of Python interpreter to call. I am not sure, but I believe that solution does not solve the problem for Microsoft Windows platform users.
In the Microsoft Windows world, the simplify the way to run a specific Python version, without environment variables setup specifically for each specific version of Python installed, is just by prefixing the python.exe with the path you want to run it from, such as C:\Python25\python.exe mymodule.py or D:\Python27\python.exe mymodule.py
However you'd need to consider the PYTHONPATH and other PYTHON... environment variables that would point to the wrong version of Python libraries.
For example, you might run: C:\Python2.5.2\python.exe mymodule
Yet, the environment variables may point to the wrong version as such:
PYTHONPATH = D:\Python27
PYTHONLIB = D:\Python27\lib
Loads of horrible fun!
So a non-virtualenv way, in Windows, would be to use a batch file that sets up the environment and calls a specific Python executable via prefixing the python.exe with the path it resides in. This way has additional details you'll have to manage though; such as using command line arguments for either of the "start" or "cmd.exe" command to "save and replace the "console" environment" if you want the console to stick around after the application exits.
Your question leads me to believe you have several Python modules, each expecting a certain version of Python. This might be solvable "within" the script by having a launching module which uses the subprocess module. Instead of calling mymodule.py you would call a module that calls your module; perhaps launch_mymodule.py
launch_mymodule.py
import sys
import subprocess
if sys.argv[2] == '272':
env272 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch272 = subprocess.Popen('D:\\Python272\\python.exe mymodule.py', env=env272)
if sys.argv[1] == '252'
env252 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch252 = subprocess.Popen('C:\\Python252\\python.exe mymodule.py', env=env252)
I have not tested this.
How to delete duplicate lines in a file without sorting it in Unix?
awk '!seen[$0]++' file.txt
seen
is an associative-array that Awk will pass every line of the file to. If a line isn't in the array then seen[$0]
will evaluate to false. The !
is the logical NOT operator and will invert the false to true. Awk will print the lines where the expression evaluates to true. The ++
increments seen
so that seen[$0] == 1
after the first time a line is found and then seen[$0] == 2
, and so on.
Awk evaluates everything but 0
and ""
(empty string) to true. If a duplicate line is placed in seen
then !seen[$0]
will evaluate to false and the line will not be written to the output.
Extract substring from a string
When finding multiple occurrences of a substring matching a pattern
String input_string = "foo/adsfasdf/adf/bar/erqwer/";
String regex = "(foo/|bar/)"; // Matches 'foo/' and 'bar/'
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input_string);
while(matcher.find()) {
String str_matched = input_string.substring(matcher.start(), matcher.end());
// Do something with a match found
}
Excel VBA App stops spontaneously with message "Code execution has been halted"
I would try the usual remedial things:
- Run Rob Bovey's VBA Code Cleaner on your VBA Code
- remove all addins on the users PC, particularly COM and .NET addins
- Delete all the users .EXD files (MSoft Update incompatibilities)
- Run Excel Detect & Repair on the users system
- check the size of the user's .xlb file (should be 20-30K)
- Reboot then delete all the users Temp files
invalid operands of types int and double to binary 'operator%'
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the
operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
PHP: Get key from array?
Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)
How to add parameters to HttpURLConnection using POST using NameValuePair
In my case I have created function like this to make Post request which takes String url and hashmap of parameters
public String postRequest( String mainUrl,HashMap<String,String> parameterList)
{
String response="";
try {
URL url = new URL(mainUrl);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : parameterList.entrySet())
{
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0; )
sb.append((char) c);
response = sb.toString();
return response;
}catch (Exception excep){
excep.printStackTrace();}
return response;
}
Clear text from textarea with selenium
I ran into a field where .clear() did not work. Using a combination of the first two answers worked for this field.
from selenium.webdriver.common.keys import Keys
#...your code (I was using python 3)
driver.find_element_by_id('foo').send_keys(Keys.CONTROL + "a");
driver.find_element_by_id('foo').send_keys(Keys.DELETE);
How do I correctly upgrade angular 2 (npm) to the latest version?
Upgrade to latest Angular 5
Angular Dep packages:
npm install @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router}@latest --save
Other packages that are installed by the angular cli
npm install --save core-js@latest rxjs@latest zone.js@latest
Angular Dev packages:
npm install --save-dev @angular/{compiler-cli,cli,language-service}@latest
Types Dev packages:
npm install --save-dev @types/{jasmine,jasminewd2,node}@latest
Other packages that are installed as dev dev by the angular cli:
npm install --save-dev codelyzer@latest jasmine-core@latest jasmine-spec-reporter@latest karma@latest karma-chrome-launcher@latest karma-cli@latest karma-coverage-istanbul-reporter@latest karma-jasmine@latest karma-jasmine-html-reporter@latest protractor@latest ts-node@latest tslint@latest
Install the latest supported version used by the Angular cli (don't do @latest):
npm install --save-dev [email protected]
Rename file angular-cli.json to .angular-cli.json and update the content:
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "project3-example"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"styles.css"
],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json",
"exclude": "**/node_modules/**"
},
{
"project": "src/tsconfig.spec.json",
"exclude": "**/node_modules/**"
},
{
"project": "e2e/tsconfig.e2e.json",
"exclude": "**/node_modules/**"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
How do I get SUM function in MySQL to return '0' if no values are found?
Use IFNULL
or COALESCE
:
SELECT IFNULL(SUM(Column1), 0) AS total FROM...
SELECT COALESCE(SUM(Column1), 0) AS total FROM...
The difference between them is that IFNULL
is a MySQL extension that takes two arguments, and COALESCE
is a standard SQL function that can take one or more arguments. When you only have two arguments using IFNULL
is slightly faster, though here the difference is insignificant since it is only called once.
Class has no member named
Maybe I am 6.5 years late. But I'm answering because others maybe searching still now. I faced the same problem and was searching everywhere. But then I realized I had written my code in an empty file. If you create a project and write your code in there, there won't be this error.
How can I move HEAD back to a previous location? (Detached head) & Undo commits
Today, I mistakenly checked out on a commit and started working on it, making some commits on a detach HEAD state. Then I pushed to the remote branch using the following command:
git push origin HEAD: <My-remote-branch>
Then
git checkout <My-remote-branch>
Then
git pull
I finally got my all changes in my branch that I made in detach HEAD.
JVM heap parameters
The JVM will start with memory useage at the initial heap level. If the maxheap is higher, it will grow to the maxheap size as memory requirements exceed it's current memory.
So,
JVM starts with 512 M, never resizes.
JVM starts with 64M, grows (up to max ceiling of 512) if mem. requirements exceed 64.
How to display binary data as image - extjs 4
In front-end JavaScript/HTML, you can load a binary file as an image, you do not have to convert to base64:
<img src="http://engci.nabisco.com/artifactory/repo/folder/my-image">
my-image is a binary image file. This will load just fine.
How to destroy Fragment?
If you are in the fragment itself, you need to call this. Your fragment needs to be the fragment that is being called. Enter code:
getFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();
or if you are using supportLib
, then you need to call:
getSupportFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();
While loop in batch
@echo off
set countfiles=10
:loop
set /a countfiles -= 1
echo hi
if %countfiles% GTR 0 goto loop
pause
on the first "set countfiles" the 10 you see is the amount it will loop
the echo hi is the thing you want to loop
...i'm 5 years late
Expand/collapse section in UITableView in iOS
// -------------------------------------------------------------------------------
// tableView:viewForHeaderInSection:
// -------------------------------------------------------------------------------
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *mView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
[mView setBackgroundColor:[UIColor greenColor]];
UIImageView *logoView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 20, 20)];
[logoView setImage:[UIImage imageNamed:@"carat.png"]];
[mView addSubview:logoView];
UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
[bt setFrame:CGRectMake(0, 0, 150, 30)];
[bt setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[bt setTag:section];
[bt.titleLabel setFont:[UIFont systemFontOfSize:20]];
[bt.titleLabel setTextAlignment:NSTextAlignmentCenter];
[bt.titleLabel setTextColor:[UIColor blackColor]];
[bt setTitle: @"More Info" forState: UIControlStateNormal];
[bt addTarget:self action:@selector(addCell:) forControlEvents:UIControlEventTouchUpInside];
[mView addSubview:bt];
return mView;
}
#pragma mark - Suppose you want to hide/show section 2... then
#pragma mark add or remove the section on toggle the section header for more info
- (void)addCell:(UIButton *)bt{
// If section of more information
if(bt.tag == 2) {
// Initially more info is close, if more info is open
if(ifOpen) {
DLog(@"close More info");
// Set height of section
heightOfSection = 0.0f;
// Reset the parameter that more info is closed now
ifOpen = NO;
}else {
// Set height of section
heightOfSection = 45.0f;
// Reset the parameter that more info is closed now
DLog(@"open more info again");
ifOpen = YES;
}
//[self.tableView reloadData];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationFade];
}
}// end addCell
#pragma mark -
#pragma mark What will be the height of the section, Make it dynamic
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section == 2) {
return heightOfSection;
}else {
return 45.0f;
}
// vKj
How to insert element as a first child?
parentElement.prepend(newFirstChild);
This is a new addition in (likely) ES7. It is now vanilla JS, probably due to the popularity in jQuery. It is currently available in Chrome, FF, and Opera. Transpilers should be able to handle it until it becomes available everywhere.
P.S. You can directly prepend strings
parentElement.prepend('This text!');
Links: developer.mozilla.org - Polyfill
What is useState() in React?
useState is a hook that lets you add state to a functional component. It accepts an argument which is the initial value of the state property and returns the current value of state property and a method which is capable of updating that state property.
Following is a simple example:
import React, {useState} from react
function HookCounter {
const [count, stateCount]= useState(0)
return(
<div>
<button onClick{( ) => setCount(count+1)}> count{count}</button>
</div>
)
}
useState accepts the initial value of the state variable which is zero in this case and returns a pair of values. The current value of the state has been called count and a method that can update the state variable has been called as setCount.
Remove unwanted parts from strings in a column
i'd use the pandas replace function, very simple and powerful as you can use regex. Below i'm using the regex \D to remove any non-digit characters but obviously you could get quite creative with regex.
data['result'].replace(regex=True,inplace=True,to_replace=r'\D',value=r'')
Add new column in Pandas DataFrame Python
You just do an opposite comparison. if Col2 <= 1
. This will return a boolean Series with False
values for those greater than 1 and True
values for the other. If you convert it to an int64
dtype, True
becomes 1
and False
become 0
,
df['Col3'] = (df['Col2'] <= 1).astype(int)
If you want a more general solution, where you can assign any number to Col3
depending on the value of Col2
you should do something like:
df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)
Or:
df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55
Openssl is not recognized as an internal or external command
I used this code:
This is worked for me successfully.
"C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe" -exportcert -alias sociallisting -
keystore "D:\keystore\SocialListing" | "C:\cygwin\bin\openssl.exe" sha1 -binary |
"C:\cygwin\bin\openssl.exe" base64
How do I get the name of a Ruby class?
If you want to get a class name from inside a class method, class.name
or self.class.name
won't work. These will just output Class
, since the class of a class is Class
. Instead, you can just use name
:
module Foo
class Bar
def self.say_name
puts "I'm a #{name}!"
end
end
end
Foo::Bar.say_name
output:
I'm a Foo::Bar!
How do I center a Bootstrap div with a 'spanX' class?
Define the width as 960px, or whatever you prefer, and you're good to go!
#main {
margin: 0 auto !important;
float: none !important;
text-align: center;
width: 960px;
}
(I couldn't figure this out until I fixed the width, nothing else worked.)
Disabling and enabling a html input button
Using Javascript
Using jQuery
All versions of jQuery prior to 1.6
All versions of jQuery after 1.6
Disabling a html button
$('#Button').prop('disabled', true);
Enabling a html button
$('#Button').prop('disabled', false);
Demo Here
P.S. Updated the code based on jquery 1.6.1 changes. As a suggestion, always use the latest jquery files and the prop()
method.
How do you get a string from a MemoryStream?
A slightly modified version of Brian's answer allows optional management of read start, This seems to be the easiest method. probably not the most efficient, but easy to understand and use.
Public Function ReadAll(ByVal memStream As MemoryStream, Optional ByVal startPos As Integer = 0) As String
' reset the stream or we'll get an empty string returned
' remember the position so we can restore it later
Dim Pos = memStream.Position
memStream.Position = startPos
Dim reader As New StreamReader(memStream)
Dim str = reader.ReadToEnd()
' reset the position so that subsequent writes are correct
memStream.Position = Pos
Return str
End Function
How to verify CuDNN installation?
I have cuDNN 8.0 and none of the suggestions above worked for me. The desired information was in /usr/include/cudnn_version.h
, so
cat /usr/include/cudnn_version.h | grep CUDNN_MAJOR -A 2
did the trick.
script to map network drive
Does this not work (assuming "ROUTERNAME" is the user name the router expects)?
net use Z: "\\10.0.1.1\DRIVENAME" /user:"ROUTERNAME" "PW"
Alternatively, you can use use a small VBScript:
Option Explicit
Dim u, p, s, l
Dim Network: Set Network= CreateObject("WScript.Network")
l = "Z:"
s = "\\10.0.1.1\DRIVENAME"
u = "ROUTERNAME"
p = "PW"
Network.MapNetworkDrive l, s, False, u, p
Number of visitors on a specific page
If you want to know the number of visitors (as is titled in the question) and not the number of pageviews, then you'll need to create a custom report.
Terminology
Google Analytics has changed the terminology they use within the reports. Now, visits is named "sessions" and unique visitors is named "users."
User - A unique person who has visited your website. Users may visit your website multiple times, and they will only be counted once.
Session - The number of different times that a visitor came to your site.
Pageviews - The total number of pages that a user has accessed.
Creating a Custom Report
- To create a custom report, click on the "Customization" item in the left navigation menu, and then click on "Custom Reports".
- The "Create Custom Report" page will open.
- Enter a name for your report.
- In the "Metric Groups" section, enter either "Users" or "Sessions" depending on what information you want to collect (see Terminology, above).
- In the "Dimension Drilldowns" section, enter "Page".
- Under "Filters" enter the individual page (exact) or group of pages (using regex) that you would like to see the data for.
- Save the report and run it.
Why functional languages?
I think the biggest argument for functional programming languages to become the "next big thing" is that in the future multi-core processors will be the norm. Programmers will have to take advantage of that, and functional programming offers really wonderful possibilities for building top of the line concurrent software.
P.S. When I was in college at Boston University ('98-'02) we spent a semester learning Scheme which is a close cousin of LISP. When we first started learning it, I wanted to rip my hair out. By the end of the course it was very natural.
Set the absolute position of a view
Try below code to set view on specific location :-
TextView textView = new TextView(getActivity());
textView.setId(R.id.overflowCount);
textView.setText(count + "");
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
textView.setTextColor(getActivity().getResources().getColor(R.color.white));
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// to handle click
}
});
// set background
textView.setBackgroundResource(R.drawable.overflow_menu_badge_bg);
// set apear
textView.animate()
.scaleXBy(.15f)
.scaleYBy(.15f)
.setDuration(700)
.alpha(1)
.setInterpolator(new BounceInterpolator()).start();
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
layoutParams.topMargin = 100; // margin in pixels, not dps
layoutParams.leftMargin = 100; // margin in pixels, not dps
textView.setLayoutParams(layoutParams);
// add into my parent view
mainFrameLaout.addView(textView);
Connect to SQL Server database from Node.js
msnodesql is working out great for me. Here is a sample:
var mssql = require('msnodesql'),
express = require('express'),
app = express(),
nconf = require('nconf')
nconf.env()
.file({ file: 'config.json' });
var conn = nconf.get("SQL_CONN");
var conn_str = "Driver={SQL Server Native Client 11.0};Server=server.name.here;Database=Product;Trusted_Connection={Yes}";
app.get('/api/brands', function(req, res){
var data = [];
var jsonObject = {};
mssql.open(conn_str, function (err, conn) {
if (err) {
console.log("Error opening the connection!");
return;
}
conn.queryRaw("dbo.storedproc", function (err, results) {
if(err) {
console.log(err);
res.send(500, "Cannot retrieve records.");
}
else {
//res.json(results);
for (var i = 0; i < results.rows.length; i++) {
var jsonObject = new Object()
for (var j = 0; j < results.meta.length; j++) {
paramName = results.meta[j].name;
paramValue = results.rows[i][j];
jsonObject[paramName] = paramValue;
}
data.push(jsonObject); //This is a js object we are jsonizing not real json until res.send
}
res.send(data);
}
});
});
});
get data from mysql database to use in javascript
To do with javascript you could do something like this:
<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>
Then you can use whatever you want in your javascript to put the text var into the textbox.
Split text with '\r\n'
This worked for me.
string stringSeparators = "\r\n";
string text = sr.ReadToEnd();
string lines = text.Replace(stringSeparators, "");
lines = lines.Replace("\\r\\n", "\r\n");
Console.WriteLine(lines);
The first replace replaces the \r\n
from the text file's new lines, and the second replaces the actual \r\n
text that is converted to \\r\\n
when the files is read. (When the file is read \
becomes \\
).
iOS: Compare two dates
According to Apple documentation of NSDate compare:
Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.
- (NSComparisonResult)compare:(NSDate *)anotherDate
Parameters anotherDate
The date with which to compare the
receiver. This value must not be nil.
If the value is nil, the behavior is
undefined and may change in future
versions of Mac OS X.
Return Value
If:
The receiver and anotherDate are
exactly equal to each other,
NSOrderedSame
The receiver is later in
time than anotherDate,
NSOrderedDescending
The receiver is
earlier in time than anotherDate,
NSOrderedAscending
In other words:
if ([date1 compare:date2] == NSOrderedSame) ...
Note that it might be easier in your particular case to read and write this :
if ([date2 isEqualToDate:date2]) ...
See Apple Documentation about this one.
Saving results with headers in Sql Server Management Studio
Another possibility is to use the clipboard to copy and paste the results directly into Excel. Just be careful with General type Excel columns, as they can sometimes have unpredictable results, depending on your data. CTL-A
anywhere in the result grid, and then right-click:
If you have trouble with Excel's General format doing undesired conversions, select the blank columns in Excel before you paste and change the format to "text".
how to zip a folder itself using java
Try this:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Zip {
public static void main(String[] a) throws Exception {
zipFolder("D:\\reports\\january", "D:\\reports\\january.zip");
}
static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
}
}
}
}
How can I generate a unique ID in Python?
unique and random are mutually exclusive. perhaps you want this?
import random
def uniqueid():
seed = random.getrandbits(32)
while True:
yield seed
seed += 1
Usage:
unique_sequence = uniqueid()
id1 = next(unique_sequence)
id2 = next(unique_sequence)
id3 = next(unique_sequence)
ids = list(itertools.islice(unique_sequence, 1000))
no two returned id is the same (Unique) and this is based on a randomized seed value
How to hide iOS status bar
Swift 5
Use following steps to hide iOS Status Bar:
- Open on Info.plist.
- Add new key View controller-based status bar appearance and value set to NO.
- Add new key Status bar is initially hidden and value set to YES.
- Re-compile project.
- Status bar should hidden on iOS phone now.
Final Settings Screenshot:
This is working on Xcode 10.2