After 2 hrs of net surfing Finally For me the problem was fixed by creating a folder pip, with a file: pip.ini in C:\Users<username>\AppData\Roaming\ e.g:
C:\Users\<username>\AppData\Roaming\pip\pip.ini
Inside it I wrote:
[global]
trusted-host = pypi.python.org
pypi.org
files.pythonhosted.org
I restarted python, and then pip permanently trusted these sites, and used them to download packages from.
If you can't find the AppData Folder on windows, write %appdata% in file explorer and it should appear.
If the command should work with both tabs and spaces as the delimiter I would use awk
:
awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile
As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for
loop:
awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile
If you want to use cut
, you need to use the -f
option:
cut -f100-105 myfile > outfile
If the field delimiter is different from TAB
you need to specify it using -d
:
cut -d' ' -f100-105 myfile > outfile
Check the man page for more info on the cut command.
In Windows 7
mysqld.exe --install
That's all
ok guys, i think i improved the source code to be able to let the image load before trying to find out its properties, otherwise it will display '0 * 0', because the next statement would have been called before the file was loaded into the browser. Requires jquery...
function getImgSize(imgSrc){
var newImg = new Image();
newImg.src = imgSrc;
var height = newImg.height;
var width = newImg.width;
p = $(newImg).ready(function(){
return {width: newImg.width, height: newImg.height};
});
alert (p[0]['width']+" "+p[0]['height']);
}
There are many freewares to examine the certificates and key stores such as KeyStore Explorer.
Unzip the apk and open the META-INF/?.RSA file. ? shall be CERT or ANDROID or may be something else. It will display all the information associated with your apk.
In order to view only first few entries you can use, pandas head function which is used as
dataframe.head(any number) // default is 5
dataframe.head(n=value)
or you can also you slicing for this purpose, which can also give the same result,
dataframe[:n]
In order to view the last few entries you can use pandas tail() in a similar way,
dataframe.tail(any number) // default is 5
dataframe.tail(n=value)
You're nearly there, just take out the EXECUTE:
DECLARE
procId NUMBER;
BEGIN
PKG1.INIT(1143824, 0, procId);
DBMS_OUTPUT.PUT_LINE(procId);
END;
My answer is similar to the others. If you do not want to create a new function you can use what pandas has defined for you already. Use the pipe method.
df.pipe(lambda d: d[d['column'] == value])
A better trick, so you don't lose the value of the button is
function showwait() {
document.getElementById('WAIT').style['display']='inline';
document.getElementById('BUTTONS').style['display']='none';
}
wrap code to show in a div
id=WAIT style="display:none"> text to display (end div)
wrap code to hide in a div
id=BUTTONS style="display:inline"> ... buttons or whatever to hide with
onclick="showwait();"
(end div)
the most important thing is to analyze how roads, cities, blocks and buildings are structured. find out what all eg buildings have in common. look at photos, maps, plans and reality. if you do that you will be one step ahead of people who consider city building as a merely computer-technological matter.
next you should develop solutions on how to create that geometry in tiny, distinct steps. you have to define rules that make up a believable city. if you are into 3d modelling you have to rethink a lot of what you have learned so the computer can follow your instructions in any situation.
in order to not loose track you should set up a lot of operators that are only responsible for little parts of the whole process. that makes debugging, expanding and improving your system much easier. in the next step you should link those operators and check the results by changing parameters.
i have seen too many "city generators" that mainly consist of random-shaped boxes with some window textures on them : (
Modified from this link. This will return as string, but you can modify as needed to return your datetime data type.
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(GetDate())-1),GetDate()),101)
You can use
import heapq
listForTree = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
heapq.heapify(listForTree) # for a min heap
heapq._heapify_max(listForTree) # for a maxheap!!
If you then want to pop elements, use:
heapq.heappop(minheap) # pop from minheap
heapq._heappop_max(maxheap) # pop from maxheap
For application-wide settings and for global constants I recommend to use Settingslogic. This settings are stored in YML file and can be accessed from models, views and controllers. Furthermore, you can create different settings for all your environments:
# app/config/application.yml
defaults: &defaults
cool:
sweet: nested settings
neat_setting: 24
awesome_setting: <%= "Did you know 5 + 5 = #{5 + 5}?" %>
colors: "white blue black red green"
development:
<<: *defaults
neat_setting: 800
test:
<<: *defaults
production:
<<: *defaults
Somewhere in the view (I prefer helper methods for such kind of stuff) or in a model you can get, for ex., array of colors Settings.colors.split(/\s/)
. It's very flexible. And you don't need to invent a bike.
No package.json is necessery to change.
For me it works using:
ng serve --host=0.0.0.0 --port=5999 --disable-host-check
Host: http://localhost:5999/
\n
is a line break. /n
is not.
use of \n
with
Now if you are trying to echo string to the page:
echo "kings \n garden";
output will be:
kings garden
you won't get garden
in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n
. You need to use the nl2br()
function for that.
What it does is:
Returns string with
<br />
or<br>
inserted before all newlines (\r\n, \n\r, \n and \r).
echo nl2br ("kings \n garden");
kings
garden
Note Make sure you're echoing/printing
\n
in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is
so "\n" not '\n'
Now if you echo to text file you can use just \n
and it will echo to a new line, like:
$myfile = fopen("test.txt", "w+") ;
$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
output will be:
kings
garden
You will need to put a quote at the beginning of your first text and the end of your last.
GLib is a portability/utility library for C which forms the basis of the GTK+ graphical toolkit. It can be used as a standalone library.
It contains portable wrappers for managing directories. See Glib File Utilities documentation for details.
Personally, I wouldn't even consider writing large amounts of C-code without something like GLib behind me. Portability is one thing, but it's also nice to get data structures, thread helpers, events, mainloops etc. for free
Jikes, I'm almost starting to sound like a sales guy :) (don't worry, glib is open source (LGPL) and I'm not affiliated with it in any way)
I design & implemented a simple finite state machine example with java.
IFiniteStateMachine: The public interface to manage the finite state machine
such as add new states to the finite state machine or transit to next states by
specific actions.
interface IFiniteStateMachine {
void setStartState(IState startState);
void setEndState(IState endState);
void addState(IState startState, IState newState, Action action);
void removeState(String targetStateDesc);
IState getCurrentState();
IState getStartState();
IState getEndState();
void transit(Action action);
}
IState: The public interface to get state related info
such as state name and mappings to connected states.
interface IState {
// Returns the mapping for which one action will lead to another state
Map<String, IState> getAdjacentStates();
String getStateDesc();
void addTransit(Action action, IState nextState);
void removeTransit(String targetStateDesc);
}
Action: the class which will cause the transition of states.
public class Action {
private String mActionName;
public Action(String actionName) {
mActionName = actionName;
}
String getActionName() {
return mActionName;
}
@Override
public String toString() {
return mActionName;
}
}
StateImpl: the implementation of IState. I applied data structure such as HashMap to keep Action-State mappings.
public class StateImpl implements IState {
private HashMap<String, IState> mMapping = new HashMap<>();
private String mStateName;
public StateImpl(String stateName) {
mStateName = stateName;
}
@Override
public Map<String, IState> getAdjacentStates() {
return mMapping;
}
@Override
public String getStateDesc() {
return mStateName;
}
@Override
public void addTransit(Action action, IState state) {
mMapping.put(action.toString(), state);
}
@Override
public void removeTransit(String targetStateDesc) {
// get action which directs to target state
String targetAction = null;
for (Map.Entry<String, IState> entry : mMapping.entrySet()) {
IState state = entry.getValue();
if (state.getStateDesc().equals(targetStateDesc)) {
targetAction = entry.getKey();
}
}
mMapping.remove(targetAction);
}
}
FiniteStateMachineImpl: Implementation of IFiniteStateMachine. I use ArrayList to keep all the states.
public class FiniteStateMachineImpl implements IFiniteStateMachine {
private IState mStartState;
private IState mEndState;
private IState mCurrentState;
private ArrayList<IState> mAllStates = new ArrayList<>();
private HashMap<String, ArrayList<IState>> mMapForAllStates = new HashMap<>();
public FiniteStateMachineImpl(){}
@Override
public void setStartState(IState startState) {
mStartState = startState;
mCurrentState = startState;
mAllStates.add(startState);
// todo: might have some value
mMapForAllStates.put(startState.getStateDesc(), new ArrayList<IState>());
}
@Override
public void setEndState(IState endState) {
mEndState = endState;
mAllStates.add(endState);
mMapForAllStates.put(endState.getStateDesc(), new ArrayList<IState>());
}
@Override
public void addState(IState startState, IState newState, Action action) {
// validate startState, newState and action
// update mapping in finite state machine
mAllStates.add(newState);
final String startStateDesc = startState.getStateDesc();
final String newStateDesc = newState.getStateDesc();
mMapForAllStates.put(newStateDesc, new ArrayList<IState>());
ArrayList<IState> adjacentStateList = null;
if (mMapForAllStates.containsKey(startStateDesc)) {
adjacentStateList = mMapForAllStates.get(startStateDesc);
adjacentStateList.add(newState);
} else {
mAllStates.add(startState);
adjacentStateList = new ArrayList<>();
adjacentStateList.add(newState);
}
mMapForAllStates.put(startStateDesc, adjacentStateList);
// update mapping in startState
for (IState state : mAllStates) {
boolean isStartState = state.getStateDesc().equals(startState.getStateDesc());
if (isStartState) {
startState.addTransit(action, newState);
}
}
}
@Override
public void removeState(String targetStateDesc) {
// validate state
if (!mMapForAllStates.containsKey(targetStateDesc)) {
throw new RuntimeException("Don't have state: " + targetStateDesc);
} else {
// remove from mapping
mMapForAllStates.remove(targetStateDesc);
}
// update all state
IState targetState = null;
for (IState state : mAllStates) {
if (state.getStateDesc().equals(targetStateDesc)) {
targetState = state;
} else {
state.removeTransit(targetStateDesc);
}
}
mAllStates.remove(targetState);
}
@Override
public IState getCurrentState() {
return mCurrentState;
}
@Override
public void transit(Action action) {
if (mCurrentState == null) {
throw new RuntimeException("Please setup start state");
}
Map<String, IState> localMapping = mCurrentState.getAdjacentStates();
if (localMapping.containsKey(action.toString())) {
mCurrentState = localMapping.get(action.toString());
} else {
throw new RuntimeException("No action start from current state");
}
}
@Override
public IState getStartState() {
return mStartState;
}
@Override
public IState getEndState() {
return mEndState;
}
}
example:
public class example {
public static void main(String[] args) {
System.out.println("Finite state machine!!!");
IState startState = new StateImpl("start");
IState endState = new StateImpl("end");
IFiniteStateMachine fsm = new FiniteStateMachineImpl();
fsm.setStartState(startState);
fsm.setEndState(endState);
IState middle1 = new StateImpl("middle1");
middle1.addTransit(new Action("path1"), endState);
fsm.addState(startState, middle1, new Action("path1"));
System.out.println(fsm.getCurrentState().getStateDesc());
fsm.transit(new Action(("path1")));
System.out.println(fsm.getCurrentState().getStateDesc());
fsm.addState(middle1, endState, new Action("path1-end"));
fsm.transit(new Action(("path1-end")));
System.out.println(fsm.getCurrentState().getStateDesc());
fsm.addState(endState, middle1, new Action("path1-end"));
}
}
You seem to be using Python as if it were the shell. Whenever I've needed to do something like what you're doing, I've used os.walk()
For example, as explained here: [x[0] for x in os.walk(directory)]
should give you all of the subdirectories, recursively.
Better and easier git log by making an alias. Paste the code below to terminal just once for one session. Paste the code to zshrc or bash profile to make it persistant.
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
Output
git lg
Output changed lines
git lg -p
Alternatively (recommended)
Paste this code to global .gitconfig file
[alias]
lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
Further Reading.
https://coderwall.com/p/euwpig/a-better-git-log
Advanced Reading.
http://durdn.com/blog/2012/11/22/must-have-git-aliases-advanced-examples/
"The mathematical notion of modulo arithmetic works for floating point values as well, and this is one of the first issues that Donald Knuth discusses in his classic The Art of Computer Programming (volume I). I.e. it was once basic knowledge."
The floating point modulus operator is defined as follows:
m = num - iquot*den ; where iquot = int( num/den )
As indicated, the no-op of the % operator on floating point numbers appears to be standards related. The CRTL provides 'fmod', and usually 'remainder' as well, to perform % on fp numbers. The difference between these two lies in how they handle the intermediate 'iquot' rounding.
'remainder' uses round-to-nearest, and 'fmod' uses simple truncate.
If you write your own C++ numerical classes, nothing prevents you from amending the no-op legacy, by including an overloaded operator %.
Best Regards
In a single SQL query, without using the FOR XML clause.
A Common Table Expression is used to recursively concatenate the results.
-- rank locations by incrementing lexicographical order
WITH RankedLocations AS (
SELECT
VehicleID,
City,
ROW_NUMBER() OVER (
PARTITION BY VehicleID
ORDER BY City
) Rank
FROM
Locations
),
-- concatenate locations using a recursive query
-- (Common Table Expression)
Concatenations AS (
-- for each vehicle, select the first location
SELECT
VehicleID,
CONVERT(nvarchar(MAX), City) Cities,
Rank
FROM
RankedLocations
WHERE
Rank = 1
-- then incrementally concatenate with the next location
-- this will return intermediate concatenations that will be
-- filtered out later on
UNION ALL
SELECT
c.VehicleID,
(c.Cities + ', ' + l.City) Cities,
l.Rank
FROM
Concatenations c -- this is a recursion!
INNER JOIN RankedLocations l ON
l.VehicleID = c.VehicleID
AND l.Rank = c.Rank + 1
),
-- rank concatenation results by decrementing length
-- (rank 1 will always be for the longest concatenation)
RankedConcatenations AS (
SELECT
VehicleID,
Cities,
ROW_NUMBER() OVER (
PARTITION BY VehicleID
ORDER BY Rank DESC
) Rank
FROM
Concatenations
)
-- main query
SELECT
v.VehicleID,
v.Name,
c.Cities
FROM
Vehicles v
INNER JOIN RankedConcatenations c ON
c.VehicleID = v.VehicleID
AND c.Rank = 1
Spring is three things.
The problem is that Spring DI is really well thought out, the wrappers around other things are really well thought out in that the other things thought everything out and Spring just nicely wraps it. The Spring implementations of MVC and REST and all the other stuff is not as well done (YMMV, IMHO) but there are exceptions (Spring Security is da bomb). So I tend to use Spring for DI, and its cool wrappers but prefer other stuff for Web (I like Tapestry a lot), REST (Jersey is really robust), etc.
Excel 2010 - if you're looking to reorder the series on a pivot chart:
please try this
echo $VAR | grep ClNonZ | awk '{print $3}';
or
echo cat filename | grep ClNonZ | awk '{print $3}';
In my case, I was using both @RunWith(MockitoJUnitRunner.class)
and MockitoAnnotations.initMocks(this)
. When I removed MockitoAnnotations.initMocks(this)
it worked correctly.
A trick if you want to keep the order of the list:
df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
countries_to_keep = ['Germany', 'US']
ind=[df.index[df['country']==i].tolist() for i in countries_to_keep]
flat_ind=[item for sublist in ind for item in sublist]
df.reindex(flat_ind)
country
2 Germany
0 US
Avoiding redundancy I don't repeat my answer here again.
Please refer to my answer here. (note that answer only covers compiling to python bytecode.)
Late to the party, but I think this is actually the most elegant. Use the WORD JOINER Unicode character ⁠ on either side of your hyphen, or em dash, or any character.
So, like so:
⁠—⁠
This will join the symbol on both ends to its neighbors (without adding a space) and prevent line breaking.
I had the same problem when tom?at could not find the class. Try to view other log files. Sometimes No class def found error appears in different log files:
If you are using jQuery you can use the extend function to add new items.
var olddata = {"fruit":{"apples":10,"pears":21}};
var newdata = {};
newdata['vegetables'] = {"carrots": 2, "potatoes" : 5};
$.extend(true, olddata, newdata);
This will generate:
{"fruit":{"apples":10,"pears":21}, "vegetables":{"carrots":2,"potatoes":5}};
I can't find toByteArray()
as @atrioom said, so I use StringWriter
, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString
:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
ignorecase
to false
in git configAs the original post is about "Changing capitalization of filenames in Git":
If you are trying to change capitalisation of a filename in your project, you do not need to force rename it from Git. IMO, I would rather change the capitalisation from my IDE/editor and make sure that I configure Git properly to pick up the renaming.
By default, a Git template is set to ignore case (Git case insensitive). To verify you have the default template, use --get
to retrieve the value for a specified key. Use --local
and --global
to indicate to Git whether to pick up a configuration key-value from your local Git repository configuration or global one. As an example, if you want to lookup your global key core.ignorecase
:
git config --global --get core.ignorecase
If this returns true
, make sure to set it as:
git config --global core.ignorecase false
(Make sure you have proper permissions to change global.) And there you have it; now your Git installation would not ignore capitalisations and treat them as changes.
As a suggestion, if you are working on multi-language projects and you feel not all projects should be treated as case-sensitive by Git, just update the local core.ignorecase
file.
As of Notepad++ 5.9 they added a feature to 'Remove Unmarked Lines' which can be used to strip away everything that you don't want along with some search and replaces for the other text on each value line.
You can also do a similar thing using Search-->Bookmark-->Copy Bookmarked Lines
So technically you still cannot copy marked text, but you can bookmark lines with marked text and then perform various operations on bookmarked or unmarked lines.
1.Export a Secret Key (this is what your boss should have done for you)
gpg --export-secret-keys yourKeyName > privateKey.asc
2.Import Secret Key (import your privateKey)
gpg --import privateKey.asc
3.Not done yet, you still need to ultimately trust a key. You will need to make sure that you also ultimately trust a key.
gpg --edit-key yourKeyName
Enter trust, 5, y, and then quit
Source: https://medium.com/@GalarnykMichael/public-key-asymmetric-cryptography-using-gpg-5a8d914c9bca
The stroke doubles up on the middel sections, I used this layer list drawable:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/grey" />
</shape>
</item>
<item android:top="1dp" android:left="1dp" android:bottom="1dp" android:right="1dp">
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/lightgrey" />
</shape>
</item>
</layer-list>
If using requestFocus()
in onCreate()
introduces the issue of keyboard not showing on tap, use BindingAdapter
using a SingleLiveEvent and request the focus inside that.
Here's how to do it:
BindingAdapter
@BindingAdapter("requestFocus")
fun bindRequestFocus(editText: EditText, event: Event<Boolean>?) {
event?.getContentIfNotHandled()?.let {
if (it) editText.requestFocus()
}
}
You can check your indexes in MySQL workbench.under the performance reports tabs you can see all used indexes and unused indexes on the system. or you can fire the query.
select * from sys.schema_index_statistics;
What are the differences in the applications of
Runnable
andCallable
. Is the difference only with the return parameter present inCallable
?
Basically, yes. See the answers to this question. And the javadoc for Callable
.
What is the need of having both if
Callable
can do all thatRunnable
does?
Because the Runnable
interface cannot do everything that Callable
does!
Runnable
has been around since Java 1.0, but Callable
was only introduced in Java 1.5 ... to handle use-cases that Runnable
does not support. In theory, the Java team could have changed the signature of the Runnable.run()
method, but this would have broken binary compatiblity with pre-1.5 code, requiring recoding when migrating old Java code to newer JVMs. That is a BIG NO-NO. Java strives to be backwards compatible ... and that's been one of Java's biggest selling points for business computing.
And, obviously, there are use-cases where a task doesn't need to return a result or throw a checked exception. For those use-cases, using Runnable
is more concise than using Callable<Void>
and returning a dummy (null
) value from the call()
method.
An alternative implementation in pure powershell (without Add-Type
of c# source):
#requires -Version 5
#requires -PSEdition Desktop
class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
[bool] CheckValidationResult([System.Net.ServicePoint] $a,
[System.Security.Cryptography.X509Certificates.X509Certificate] $b,
[System.Net.WebRequest] $c,
[int] $d) {
return $true
}
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()
if "allow zero datetime=true" is not working then use the following sollutions:-
Add this to your connection string: "allow zero datetime=no" - that made the type cast work perfectly.
Sorry to post answer for very old thread. my answer may help other in future.
string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);
//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
DataTable dtUniqRecords = new DataTable();
dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
return dtUniqRecords;
}
Try this function for get root directory path:
get_template_directory_uri();
An RPC style web service uses the names of the method and its parameters to generate XML structures representing a method’s call stack. Document style indicates the SOAP body contains an XML document which can be validated against pre-defined XML schema document.
A good starting point : SOAP Binding: Difference between Document and RPC Style Web Services
Another thought occurred to me just now that could be a pure CSS solution. Display your active class as an absolutely positioned block and set its style to cover up the parent li.
a.active {
position:absolute;
display:block;
width:100%;
height:100%;
top:0em;
left:0em;
background-color: whatever;
border: whatever;
}
/* will also need to make sure the parent li is a positioned element so... */
ul.menu li {
position:relative;
}
For those of you who want to use javascript without jquery...
Selecting the parent is trivial. You need a getElementsByClass
function of some sort, unless you can get your drupal plugin to assign the active item an ID instead of Class. The function I provided I grabbed from some other genius on SO. It works well, just keep in mind when you're debugging that the function will always return an array of nodes, not just a single node.
active_li = getElementsByClass("active","a");
active_li[0].parentNode.style.whatever="whatever";
function getElementsByClass(node,searchClass,tag) {
var classElements = new Array();
var els = node.getElementsByTagName(tag); // use "*" for all elements
var elsLen = els.length;
var pattern = new RegExp("\\b"+searchClass+"\\b");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
here is the code to print only the headers or columns of the csv file.
import csv
HEADERS = next(csv.reader(open('filepath.csv')))
print (HEADERS)
Another method with pandas
import pandas as pd
HEADERS = list(pd.read_csv('filepath.csv').head(0))
print (HEADERS)
One scenario that I haven't seen people really answer, is how to have a preselection when the options are AJAX sourced, and you can select multiple. Since this is the go-to page for AJAX preselection, I'll add my solution here.
$('#mySelect').select2({
ajax: {
url: endpoint,
dataType: 'json',
data: [
{ // Each of these gets processed by fnRenderResults.
id: usersId,
text: usersFullName,
full_name: usersFullName,
email: usersEmail,
image_url: usersImageUrl,
selected: true // Causes the selection to actually get selected.
}
],
processResults: function(data) {
return {
results: data.users,
pagination: {
more: data.next !== null
}
};
}
},
templateResult: fnRenderResults,
templateSelection: fnRenderSelection, // Renders the result with my own style
selectOnClose: true
});
$data = $this->db->get_where('columnname',array('code' => 'B'));
$this->db->where_in('columnname',$data);
$this->db->where('code !=','B');
$query = $this->db->get();
return $query->result_array();
for horizontaly centering you can have something like this:
.centering{
float:none;
margin:0 auto
}
<div class="span8 centering"></div>
I know this is a little old but I wanted to add an updated answer with f-strings which were introduced in Python version 3.6:
msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'
I am using ui-router and my code looks like this:
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams){
/* Google analytics */
var path = toState.url;
for(var i in toParams){
path = path.replace(':' + i, toParams[i]);
}
/* global ga */
ga('send', 'pageview', path);
});
This way I can track different states. Maybe someone will find it usefull.
You can download the Voice using Wget:D
wget -q -U Mozilla "http://translate.google.com/translate_tts?tl=en&q=Hello"
Save the output into a mp3 file:
wget -q -U Mozilla "http://translate.google.com/translate_tts?tl=en&q=Hello" -O hello.mp3
Enjoy !!
Here is a working version using v3
of docker-compose.yml
. The key is the volumes directive:
mysql:
image: mysql:5.6
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: theusername
MYSQL_PASSWORD: thepw
MYSQL_DATABASE: mydb
volumes:
- ./data:/docker-entrypoint-initdb.d
In the directory that I have my docker-compose.yml
I have a data
dir that contains .sql
dump files. This is nice because you can have a .sql
dump file per table.
I simply run docker-compose up
and I'm good to go. Data automatically persists between stops. If you want remove the data and "suck in" new .sql
files run docker-compose down
then docker-compose up
.
If anyone knows how to get the mysql
docker to re-process files in /docker-entrypoint-initdb.d
without removing the volume, please leave a comment and I will update this answer.
Here's the solution,
If you are a constant proxy changer like me for various reasons (university, home , workplace and so on..) you are mostly likely to get this error due to improper configuration of connection settings in the eclipse IDE. all you have to do it play around with the current settings and get it to working state. Here's how,,
1. GO TO
Window-> Preferences -> General -> Network Connection.
2. Change the Settings
Active Provider-> Manual-> and check---> HTTP, HTTPS and SOCKS
If your active provider is already set to Manual, try restoring the default (native)
That's all, restart Eclipse and you are good to go!
Besides put all your assets in the public folder, you can use the HTML::image()
Method, and only needs an argument which is the path to the image, relative on the public folder, as well:
{{ HTML::image('imgs/picture.jpg') }}
Which generates the follow HTML code:
<img src="http://localhost:8000/imgs/picture.jpg">
The link to other elements of HTML::image()
Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element
The parseInt solution is the best way to go as it is clear what is happening.
For completeness it is worth mentioning that this can also be done with the + operator
$('.load_more').live("click",function() { //When user clicks
var newcurrentpageTemp = +$(this).attr("id") + 1; //Get the id from the hyperlink
alert(newcurrentpageTemp);
dosomething();
});
$("#foo > div").length
Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.
Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.
note I changed the varchar2(32000) to CLOB
set serveroutput ON
CREATE TABLE testclob
(
id NUMBER,
c CLOB,
d VARCHAR2(4000)
);
DECLARE
reallybigtextstring CLOB := '123';
i INT;
BEGIN
WHILE Length(reallybigtextstring) <= 60000 LOOP
reallybigtextstring := reallybigtextstring
|| '000000000000000000000000000000000';
END LOOP;
INSERT INTO testclob
(id,
c,
d)
VALUES (0,
reallybigtextstring,
'done');
dbms_output.Put_line('I have finished inputting your clob: '
|| Length(reallybigtextstring));
END;
/
SELECT *
FROM testclob;
"I have finished inputting your clob: 60030"
Try using step="0.01"
, then it will step by a penny each time.
eg:
<input type="number" min="0.00" max="10000.00" step="0.01" />
_x000D_
I wrote a method that handles the following edge-cases:
", ".join({'abc'})
will return "a, b, c"
. My desired output was "abc"
.""
def set_to_str(set_to_convert, separator=", "):
set_size = len(set_to_convert)
if not set_size:
return ""
elif set_size == 1:
(element,) = set_to_convert
return str(element)
else:
return separator.join(map(str, set_to_convert))
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wb = new WebView(this);
wb.loadUrl("file:///android_asset/index.html");
setContentView(wb);
}
keep your .html in `asset` folder
Get rid of the escape characters before storing or manipulating the raw string:
You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:
>>> mypath = os.getcwd().replace('\\','/')
>>> os.path.exists(mypath)
True
>>>
A shell method to read the environmental variable for this courtesy of devhut
Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")
Same source gives an API method:
Option Explicit
#If VBA7 And Win64 Then
'x64 Declarations
Declare PtrSafe Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#Else
'x32 Declaration
Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If
Public Sub test()
Debug.Print ComputerName
End Sub
Public Function ComputerName() As String
Dim sBuff As String * 255
Dim lBuffLen As Long
Dim lResult As Long
lBuffLen = 255
lResult = GetComputerName(sBuff, lBuffLen)
If lBuffLen > 0 Then
ComputerName = Left(sBuff, lBuffLen)
End If
End Function
Use the constructor for appending material to the file:
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
So to append to a file say "abc.txt" use
FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);
" once the info is added to the DB, should I delete the tuple? i mean i dont need the tuple anymore."
No.
Generally, there's no reason to delete anything. There are some special cases for deleting, but they're very, very rare.
Simply define a narrow scope (i.e., a function definition or a method function in a class) and the objects will be garbage collected at the end of the scope.
Don't worry about deleting anything.
[Note. I worked with a guy who -- in addition to trying to delete objects -- was always writing "reset" methods to clear them out. Like he was going to save them and reuse them. Also a silly conceit. Just ignore the objects you're no longer using. If you define your functions in small-enough blocks of code, you have nothing more to think about.]
I've been playing around with the preferences and added the following to my brackets.json
file (access in Menu Bar: Debug: "Open Preferences File").
"closeTags": {
"dontCloseTags": ["br", "hr", "img", "input", "link", "meta", "area", "base", "col", "command", "embed", "keygen", "param", "source", "track", "wbr"],
"indentTags": ["ul", "ol", "div", "section", "table", "tr"],
}
dontCloseTags
are tags such as <br>
which shouldn't be closed.indentTags
are tags that you want to automatically create a new
indented line - add more as needed!When This Error is Coming it is lack of the following
1)Setting the path to mongo db go to "C" Drive and the installation of Mongo db directory and then go to bin folder in the mongo and copy the path of it
c:/mongodb/server/3.2/bin/ and create a new environmental variable in system properties then name is path and value="c:/mongodb/server/3.2/bin/" here my version is 3.2
2)create a data directory for the data in C Drive c:/Data/twitter
3)start the server with **
c:/> mongod
check your port config if there is any error as the local port may be assigned to any other 4)start your Mongo database with
Mongo then your mongo db will start
then in your mongo database create a database
use DATABASE_NAME
for example:
use twitterdata
switched to db twitterdata
to check your current database
db
twitterdata
to get total databases
show dbs
The problem is that the body of the page isn't actually visible. The DIVs under have width of 100% and have background colors themselves that override the body CSS.
To Fix the no-man's land, this might work. It's not elegant, but works.
#doc3 {
margin: auto 10px;
width: auto;
height: 2000px;
background-color: yellow;
}
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
public partial class App : System.Windows.Application
{
public bool IsProcessOpen(string name)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains(name))
{
return true;
}
}
return false;
}
protected override void OnStartup(StartupEventArgs e)
{
// Get Reference to the current Process
Process thisProc = Process.GetCurrentProcess();
if (IsProcessOpen("name of application.exe") == false)
{
//System.Windows.MessageBox.Show("Application not open!");
//System.Windows.Application.Current.Shutdown();
}
else
{
// Check how many total processes have the same name as the current one
if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
{
// If ther is more than one, than it is already running.
System.Windows.MessageBox.Show("Application is already running.");
System.Windows.Application.Current.Shutdown();
return;
}
base.OnStartup(e);
}
}
This is not exactly showing you which rows are locked, but this may helpful to you.
You can check which statements are blocked by running this:
select cmd,* from sys.sysprocesses
where blocked > 0
It will also tell you what each block is waiting on. So you can trace that all the way up to see which statement caused the first block that caused the other blocks.
Edit to add comment from @MikeBlandford:
The blocked column indicates the spid of the blocking process. You can run kill {spid} to fix it.
you could use a one liner option
<div ng-repeat="key in keywords">
<button ng-click="keywords.splice($index, 1)">
{{key.name}}
</button>
</div>
$index
is used by angular to show current index of the array inside ng-repeat
Always (always, always, I'm not kidding) use htmlspecialchars()
:
echo htmlspecialchars($_POST['contact_list']);
requests
library doesn't support ftp links.
To download a file from FTP server you could:
import urllib
urllib.urlretrieve('ftp://server/path/to/file', 'file')
# if you need to pass credentials:
# urllib.urlretrieve('ftp://username:password@server/path/to/file', 'file')
Or:
import shutil
import urllib2
from contextlib import closing
with closing(urllib2.urlopen('ftp://server/path/to/file')) as r:
with open('file', 'wb') as f:
shutil.copyfileobj(r, f)
Python3:
import shutil
import urllib.request as request
from contextlib import closing
with closing(request.urlopen('ftp://server/path/to/file')) as r:
with open('file', 'wb') as f:
shutil.copyfileobj(r, f)
If you are using SQL Express (which you are), then your login credentials are .\SQLEXPRESS
Here is the connectionString in the web config file which you can add:
<connectionStrings>
<add connectionString="Server=localhost\SQLEXPRESS;Database=yourDBName;Initial Catalog= yourDBName;Integrated Security=true" name="nametoCallBy" providerName="System.Data.SqlClient"/>
</connectionStrings>
Place is just above the system.web tag.
Then you can call it by:
connString = ConfigurationManager.ConnectionStrings["nametoCallBy"].ConnectionString;
If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example:
<asp:Label runat="server" id="Label1" style="display: none;" />
Then, you could make it visible on the client side with:
document.getElementById('Label1').style.display = 'inherit';
You could make it hidden again with:
document.getElementById('Label1').style.display = 'none';
Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ.
For those who come here by search (because this thread is over 3 years old):
string entry // replace with search value
if (comboBox.Items.Contains(entry))
comboBox.SelectedIndex = comboBox.Items.IndexOf(entry);
else
comboBox.SelectedIndex = 0;
To simply combine them you can place them all together like this:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,"_AB","_"),"_CD","_"),"_EF","_"),"_40K",""),"_60K",""),"_S_","_"),"_","-")
(note that this may pass the older Excel limit of 7 nested statements. I'm testing in Excel 2010
Another way to do it is by utilizing Left
and Right
functions.
This assumes that the changing data on the end is always present and is 8 characters long
=SUBSTITUTE(LEFT(A2,LEN(A2)-8),"_","-")
This will achieve the same resulting string
If the string doesn't always end with 8 characters that you want to strip off you can search for the "_S" and get the current location. Try this:
=SUBSTITUTE(LEFT(A2,FIND("_S",A2,1)),"_","-")
Predicate
has methods and
, or
and negate
.
However, String::isEmpty
is not a Predicate
, it's just a String -> Boolean
lambda and it could still become anything, e.g. Function<String, Boolean>
. Type inference is what needs to happen first. The filter
method infers type implicitly. But if you negate it before passing it as an argument, it no longer happens. As @axtavt mentioned, explicit inference can be used as an ugly way:
s.filter(((Predicate<String>) String::isEmpty).negate()).count()
There are other ways advised in other answers, with static not
method and lambda most likely being the best ideas. This concludes the tl;dr section.
However, if you want some deeper understanding of lambda type inference, I'd like to explain it a bit more to depth, using examples. Look at these and try to figure out what happens:
Object obj1 = String::isEmpty;
Predicate<String> p1 = s -> s.isEmpty();
Function<String, Boolean> f1 = String::isEmpty;
Object obj2 = p1;
Function<String, Boolean> f2 = (Function<String, Boolean>) obj2;
Function<String, Boolean> f3 = p1::test;
Predicate<Integer> p2 = s -> s.isEmpty();
Predicate<Integer> p3 = String::isEmpty;
Predicate
to Object
- silly but validPredicate
to Function
, it's no longer about inferencetest
that is defined by its lambdaInteger
doesn't have isEmpty
methodString::isEmpty
static method with Integer
argumentI hope this helps get some more insight into how type inferrence works.
The following worked for me (tested on react native 0.38
and 0.40
):
npm install -g ios-deploy
# Run on a connected device, e.g. Max's iPhone:
react-native run-ios --device "Max's iPhone"
If you try to run run-ios
, you will see that the script recommends to do npm install -g ios-deploy
when it reach install step after building.
While the documentation on the various commands that react-native offers is a little sketchy, it is worth going to react-native/local-cli. There, you can see all the commands available and the code that they run - you can thus work out what switches are available for undocumented commands.
The ultimate solution would be setting overflow: hidden;
on document.documentElement
like so:
/* element is an HTML element You want catch the touch */
element.addEventListener('touchstart', function(e) {
document.documentElement.style.overflow = 'hidden';
});
document.addEventListener('touchend', function(e) {
document.documentElement.style.overflow = 'auto';
});
By setting overflow: hidden
on start of touch it makes everything exceeding window hidden thus removing availability to scroll anything (no content to scroll).
After touchend
the lock can be freed by setting overflow
to auto
(the default value).
It is better to append this to <html>
because <body>
may be used to do some styling, plus it can make children behave unexpectedly.
EDIT:
About touch-action: none;
- Safari doesn't support it according to MDN.
None of the other answers (with one exception, see my edit) handle the case where there are multiple trailing carriage returns. If the goal is to make a function similar to "Trim" that removes carriage returns as well as spaces, you'll probably want it to be robust enough to remove as many as there are and not just one. Also, I'd recommend avoiding the use of the "Left" or "Right" functions in VBA since they do not exist in VB.Net. It may be necessary at some point to convert an Office VBA Macro to a VSTO COM Add-In so it's a good habit to avoid the use of functions that only exist in VBA.
Function RemoveTrailingWhiteSpace(s As String) As String
RemoveTrailingWhiteSpace = s
Dim StrLen As Long
StrLen = Len(RemoveTrailingWhiteSpace)
While (StrLen > 0 And (Mid(RemoveTrailingWhiteSpace, StrLen) = vbCr Or Mid(RemoveTrailingWhiteSpace, StrLen) = vbLf) Or Mid(RemoveTrailingWhiteSpace, StrLen) = " ")
RemoveTrailingWhiteSpace = Mid(RemoveTrailingWhiteSpace, 1, StrLen - 1)
StrLen = Len(RemoveTrailingWhiteSpace)
Wend
End Function
Edit: I should clarify that there is another answer listed here that trims carriage returns and white space from both ends of the string, but it looked far more convoluted. This can be done fairly concisely.
You can do an http DELETE via a URL like /users/1/roles/2. That would be the most RESTful way to do it.
Otherwise I guess you can just pass the user id as part of the query params? Something like
$http.delete('/roles/' + roleid, {params: {userId: userID}}).then...
You can use this function to get a Resource ID:
public static int getResourseId(Context context, String pVariableName, String pResourcename, String pPackageName) throws RuntimeException {
try {
return context.getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
} catch (Exception e) {
throw new RuntimeException("Error getting Resource ID.", e)
}
}
So if you want to get a Drawable Resource ID, you can call the method like this:
getResourseId(MyActivity.this, "myIcon", "drawable", getPackageName());
(or from a fragment):
getResourseId(getActivity(), "myIcon", "drawable", getActivity().getPackageName());
For a String Resource ID you can call it like this:
getResourseId(getActivity(), "myAppName", "string", getActivity().getPackageName());
etc...
Careful: It throws a RuntimeException if it fails to find the Resource ID. Be sure to recover properly in production.
You probably get the error because your video path may be wrong in a way. Be sure your path is completely correct.
You are best keeping only some characters (whitelist) instead of removing certain characters (blacklist).
You can technically allow any character, just as long as you properly encode it. But, to answer in the spirit of the question, you should only allow these characters:
Everything else has a potentially special meaning. For example, you may think you can use +, but it can be replaced with a space. & is dangerous, too, especially if using some rewrite rules.
As with the other comments, check out the standards and specifications for complete details.
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});?
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
simple code for creating menu..
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
simple code for menu selected
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
for more detail go below link..
If you don't have DBA rights then you can use user_segments table:
select bytes/1024/1024 MB from user_segments where segment_name='Table_name'
var spl = item.Split('/')[1];
var format =spl.Split(';')[0];
stringconvert=item.Replace($"data:image/{format};base64,",String.Empty);
The "usual" solution is make a function that return an empty formGroup or a fullfilled formGroup
createFormGroup(data:any)
{
return this.fb.group({
user: [data?data.user:null],
questioning: [data?data.questioning:null, Validators.required],
questionType: [data?data.questionType, Validators.required],
options: new FormArray([this.createArray(data?data.options:null])
})
}
//return an array of formGroup
createArray(data:any[]|null):FormGroup[]
{
return data.map(x=>this.fb.group({
....
})
}
then, in SUBSCRIBE, you call the function
this.qService.editQue([params["id"]]).subscribe(res => {
this.editqueForm = this.createFormGroup(res);
});
be carefull!, your form must include an *ngIf to avoid initial error
<form *ngIf="editqueForm" [formGroup]="editqueForm">
....
</form>
I managed to solve this issue without the need to change any markup with the following piece of jQuery. I had a similar problem where I wanted a tooltip on a button that was already using data-toggle for a modal. All you will need to do here is add the title to the button.
$('[data-toggle="modal"][title]').tooltip();
data = numpy.asarray(im)
Notice:In PIL, img is RGBA. In cv2, img is BGRA.
My robust solution:
def cv_from_pil_img(pil_img):
assert pil_img.mode=="RGBA"
return cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGBA2BGRA)
We got it working by copying the routes from Router.php instead of using Auth::routes(), these are the routes you need:
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');
I tried from ubuntu terminal and I don't know why the GUI didn't show up according to tttthomasssss answer. So I followed the comment from KLDavenport and it worked. Here is the summary:
Open your terminal/command-line and type python then
>>> import nltk
.>>> nltk.download("stopwords")
This will store the stopwords corpus under the nltk_data. For my case it was /home/myusername/nltk_data/corpora/stopwords
.
If you need another corpus then visit nltk data and find the corpus with their ID. Then use the ID to download like we did for stopwords.
Looks like niether is faster or slower
public static void main(String arguments[]) {
//Build a long string
StringBuilder sb = new StringBuilder();
for(int j = 0; j < 10000; j++) {
sb.append("a really, really long string");
}
String str = sb.toString();
for (int testscount = 0; testscount < 10; testscount ++) {
//Test 1
long start = System.currentTimeMillis();
for(int c = 0; c < 10000000; c++) {
for (int i = 0, n = str.length(); i < n; i++) {
char chr = str.charAt(i);
doSomethingWithChar(chr);//To trick JIT optimistaion
}
}
System.out.println("1: " + (System.currentTimeMillis() - start));
//Test 2
start = System.currentTimeMillis();
char[] chars = str.toCharArray();
for(int c = 0; c < 10000000; c++) {
for (int i = 0, n = chars.length; i < n; i++) {
char chr = chars[i];
doSomethingWithChar(chr);//To trick JIT optimistaion
}
}
System.out.println("2: " + (System.currentTimeMillis() - start));
System.out.println();
}
}
public static void doSomethingWithChar(char chr) {
int newInt = chr << 2;
}
For long strings I'll chose the first one. Why copy around long strings? Documentations says:
public char[] toCharArray() Converts this string to a new character array.
Returns: a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
//Edit 1
I've changed the test to trick JIT optimisation.
//Edit 2
Repeat test 10 times to let JVM warm up.
//Edit 3
Conclusions:
First of all str.toCharArray();
copies entire string in memory. It can be memory consuming for long strings. Method String.charAt( )
looks up char in char array inside String class checking index before.
It looks like for short enough Strings first method (i.e. chatAt
method) is a bit slower due to this index check. But if the String is long enough, copying whole char array gets slower, and the first method is faster. The longer the string is, the slower toCharArray
performs. Try to change limit in for(int j = 0; j < 10000; j++)
loop to see it.
If we let JVM warm up code runs faster, but proportions are the same.
After all it's just micro-optimisation.
The formula is
minSdkVersion <= targetSdkVersion <= compileSdkVersion
minSdkVersion - is a marker that defines a minimum Android version on which application will be able to install. Also it is used by Lint to prevent calling API that doesn’t exist. Also it has impact on Build Time. So you can use build flavors to override minSdkVersion to maximum during the development. It will help to make build faster using all improvements that the Android team provides for us. For example some features Java 8 are available only from specific version of minSdkVersion.
targetSdkVersion - If AndroidOS version is >=
targetSdkVersion
it says Android system to turn on specific(new) behavior
changes. *Please note that some of new behaviors will be turned on by default even if thought targetSdkVersion
is <
, you should read official doc.
For example:
Starting in Android 6.0 (API level 23) Runtime Permissions
were introduced. If you set targetSdkVersion
to 22 or lower your application does not ask a user for some permission in run time.
Starting in Android 8.0 (API level 26), all notifications
must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).
Starting in Android 9 (API level 28), Web-based data directories separated by process
. If targetSdkVersion
is 28+ and you create several WebView
in different processes you will get java.lang.RuntimeException
compileSdkVersion - actually it is SDK Platform version and tells Gradle which Android SDK use to compile. When you want to use new features or debug .java
files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion
- level 28. compileSdkVersion
is not included in your APK: it is purely used at compile time
. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version
You can read more about it here. Also I would recommend you to take a look at the example of migration to Android 8.0.
The function add() returns the old date, but changes the original date :)
startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days');
alert(new_date);
This question is a bit old - as are the answers (and the tutorial as well)
The current api for setting a popupMenu in Swing is
myComponent.setComponentPopupMenu(myPopupMenu);
This way it will be shown automagically, both for mouse and keyboard triggers (the latter depends on LAF). Plus, it supports re-using the same popup across a container's children. To enable that feature:
myChild.setInheritsPopupMenu(true);
Look here at "u" and "s" patterns. First is without 'T' separator, and the second one is without timezone suffix.
If you add double paranthesis to the ngModel reference you get a two-way binding to your model property. That property can then be read and used in the event handler. In my view that is the most clean approach.
<input type="checkbox" [(ngModel)]="myModel.property" (ngModelChange)="processChange()" />
You can ignore the URL field and simply paste the viewstate into the Viewstate string box.
It does look like you have an old version; the serialisation methods changed in ASP.NET 2.0, so grab the 2.0 version
You should use setStroke
to set a stroke of the Graphics2D
object.
The example at http://www.java2s.com gives you some code examples.
The following code produces the image below:
import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;
public class FrameTest {
public static void main(String[] args) {
JFrame jf = new JFrame("Demo");
Container cp = jf.getContentPane();
cp.add(new JComponent() {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));
g2.draw(new Line2D.Float(30, 20, 80, 90));
}
});
jf.setSize(300, 200);
jf.setVisible(true);
}
}
(Note that the setStroke
method is not available in the Graphics
object. You have to cast it to a Graphics2D
object.)
This post has been rewritten as an article here.
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
In addition to previous answers, if your menu items are Categories and you want to highlight them when navigating through posts, check also for current-post-ancestor
:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
if (in_array('current-post-ancestor', $classes) || in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}
I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog
Non-uniformly distributed data can be plotted in excel in
Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.
1- Add the center point to your data series
+---------------+-------+------+
| Time | Time | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 | 12 |
| 09:00 - 10:00 | 09:30 | 13 |
| 10:00 - 11:00 | 10:30 | 10 |
| 13:00 - 14:00 | 13:30 | 5 |
| 14:00 - 15:00 | 14:30 | 14 |
+---------------+-------+------+
2- Create a Scatter Plot
3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:
Alternative Display:
To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.
1- You're going to need to add several rows where we draw the line and disjoint the data
+-------+------+
| Time | Freq |
+-------+------+
| 08:30 | 0 |
| 08:30 | 12 |
| | |
| 09:30 | 0 |
| 09:30 | 13 |
| | |
| 10:30 | 0 |
| 10:30 | 10 |
| | |
| 13:30 | 0 |
| 13:30 | 5 |
| | |
| 14:30 | 0 |
| 14:30 | 14 |
+-------+------+
2- Plot an X Y (Scatter) Chart with Lines.
3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.
Other that the differences in the default access (public/private), there is no difference.
However, some shops that code in C and C++ will use "class/struct" to indicate that which can be used in C and C++ (struct) and which are C++ only (class). In other words, in this style all structs must work with C and C++. This is kind of why there was a difference in the first place long ago, back when C++ was still known as "C with Classes."
Note that C unions work with C++, but not the other way around. For example
union WorksWithCppOnly{
WorksWithCppOnly():a(0){}
friend class FloatAccessor;
int a;
private:
float b;
};
And likewise
typedef union friend{
int a;
float b;
} class;
only works in C
I've made a library that implements incremental md5 in order to hash large files efficiently. Basically you read a file in chunks (to keep memory low) and hash it incrementally. You got basic usage and examples in the readme.
Be aware that you need HTML5 FileAPI, so be sure to check for it. There is a full example in the test folder.
Simply write to file string.Empty
, when append is set to false in StreamWriter. I think this one is easiest to understand for beginner.
private void ClearFile()
{
if (!File.Exists("TextFile.txt"))
File.Create("TextFile.txt");
TextWriter tw = new StreamWriter("TextFile.txt", false);
tw.Write(string.Empty);
tw.Close();
}
@Jay Mooney: A generic Dictionary class in .NET is actually a hash table, just with fixed types.
The code you've shown shouldn't convince anyone to use Hashtable instead of Dictionary, since both code pieces can be used for both types.
For hashtable:
foreach(object key in h.keys)
{
string keyAsString = key.ToString(); // btw, this is unnecessary
string valAsString = h[key].ToString();
System.Diagnostics.Debug.WriteLine(keyAsString + " " + valAsString);
}
For dictionary:
foreach(string key in d.keys)
{
string valAsString = d[key].ToString();
System.Diagnostics.Debug.WriteLine(key + " " + valAsString);
}
And just the same for the other one with KeyValuePair, just use the non-generic version for Hashtable, and the generic version for Dictionary.
So it's just as easy both ways, but Hashtable uses Object for both key and value, which means you will box all value types, and you don't have type safety, and Dictionary uses generic types and is thus better.
ldapwhoami -vvv -h <hostname> -p <port> -D <binddn> -x -w <passwd>
, where binddn
is the DN of the person whose credentials you are authenticating.
On success (i.e., valid credentials), you get Result: Success (0)
. On failure, you get ldap_bind: Invalid credentials (49)
.
If you install a JDK and choose to install sources too, the src.zip contains the source of ALL the public Java classes. Most of these have pretty good javadoc.
If you want to set through xml using android's default color codes, then you need to do as below:
android:background="@android:color/white"
If you have colors specified in your project's colors.xml
, then use:
android:background="@color/white"
If you want to do programmatically, then do:
linearlayout.setBackgroundColor(Color.WHITE);
If you're running Mac, as @pedro mentions ensure you have the HAXM installer dowloaded via the Android SDK Manager.
Next install it! In finder navigate to /YOUR_SDK_PATH/extras/intel/Hardware_Accelerated_Execution_Manager/
Run and install the .mpgk in the following .dmg
IntelHAXM_1.1.0_for_10.10.dmg
IntelHAXM_1.1.0_below_10.10.dmg
Example:
$cd /YOUR_SDK_PATH/extras/intel/Hardware_Accelerated_Execution_Manager/ $open IntelHAXM_1.1.0_below_10.10.dmg
You can take advantage of fschange. It’s a Linux filesystem change notification. The source code is downloadable from the above link, you can compile it yourself. fschange
can be used to keep track of file changes by reading data from a proc file (/proc/fschange). When data is written to a file, fschange reports the exact interval that has been modified instead of just saying that the file has been changed.
If you are looking for the more advanced solution, I would suggest checking Resilio Connect.
It is cross-platform, provides extended options for use and monitoring. Since it’s BitTorrent-based, it is faster than any other existing sync tool. It was written on their behalf.
Try regular expressions. You can find a certain pattern in your text and replace it with something that you want. I can't give you the exact code right now but you can test out your expressions using this.
One other gotcha that can result in "SyntaxError: Unexpected token"
exception when calling JSON.parse()
is using any of the following in the string values:
New-line characters.
Tabs (yes, tabs that you can produce with the Tab key!)
Any stand-alone slash \
(but for some reason not /
, at least not on Chrome.)
(For a full list see the String section here.)
For instance the following will get you this exception:
{
"msg" : {
"message": "It cannot
contain a new-line",
"description": "Some discription with a tabbed space is also bad",
"value": "It cannot have 3\4 un-escaped"
}
}
So it should be changed to:
{
"msg" : {
"message": "It cannot\ncontain a new-line",
"description": "Some discription with a\t\ttabbed space",
"value": "It cannot have 3\\4 un-escaped"
}
}
Which, I should say, makes it quite unreadable in JSON-only format with larger amount of text.
If you need to find database objects (e.g. tables, columns, triggers) by name - have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).
It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??
Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.
ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.
websocket-node WebSocket server and client for node.js
websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node
faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs
socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.
sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks
faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages
deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response
socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.
primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.
When to use:
use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities
use the fallback libraries when you care about browser fallbacks
use the full featured libraries when you care about channels
use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.
Where to test:
Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.
you can simply add a method (setAttributes, with "s" at the end) to "Element" prototype like:
Element.prototype.setAttributes = function(obj){
for(var prop in obj) {
this.setAttribute(prop, obj[prop])
}
}
you can define it in one line:
Element.prototype.setAttributes = function(obj){ for(var prop in obj) this.setAttribute(prop, obj[prop]) }
and you can call it normally as you call the other methods. The attributes are given as an object:
elem.setAttributes({"src": "http://example.com/something.jpeg", "height": "100%", "width": "100%"})
you can add an if statement to throw an error if the given argument is not an object.
Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
It exists, but it's hard to search for. I think most people call it the "splat" operator.
It's in the documentation as "Unpacking argument lists".
You'd use it like this: foo(*values)
. There's also one for dictionaries:
d = {'a': 1, 'b': 2}
def foo(a, b):
pass
foo(**d)
The previous answers using the ISNULL
function are correct only for MS Sql Server. The COALESCE
function will also work in SQL Server. But will also work in standard SQL database systems. In the given example:
SELECT sum(COALESCE(TotalHoursM,0))
+ COALESCE(TotalHoursT,0)
+ COALESCE(TotalHoursW,0)
+ COALESCE(TotalHoursTH,0)
+ COALESCE(TotalHoursF,0) AS TOTAL FROM LeaveRequest
This is identical to the ISNULL
solution with the only difference being the name of the function. Both work in SQL Server but, COALESCE
is ANSI standard and ISNULL
is not. Also, COALESCE
is more flexible.
ISNULL
will only work with two parameters. If the first parameter is NULL then the value of the second parameter is returned, else the value of the first is returned.
COALESCE will take 2 to 'n' (I don't know the limit of 'n') parameters and return the value of the first parameter that is not NULL
. When there are only two parameters the effect is the same as ISNULL
.
To add to tacaswell's answer, the colorbar()
function has an optional cax
input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
cax.set_xlabel('data label') # cax == cb.ax
I'm very happy with kdesvn - integrates very well with konqueror, much like trortousesvn with windows explorer, and supports most of the functionality of tortoisesvn.
Of course, you'll benefit from this integration, if you use kubunto, and not ubuntu.
Answer to add multiple markers.
UPDATE (GEOCODE MULTIPLE ADDRESSES)
Here's the working Example Geocoding with multiple addresses.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var delay = 100;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(21.0000, 78.0000);
var mapOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status)
{
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
}
}
next();
}
);
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
var locations = [
'New Delhi, India',
'Mumbai, India',
'Bangaluru, Karnataka, India',
'Hyderabad, Ahemdabad, India',
'Gurgaon, Haryana, India',
'Cannaught Place, New Delhi, India',
'Bandra, Mumbai, India',
'Nainital, Uttranchal, India',
'Guwahati, India',
'West Bengal, India',
'Jammu, India',
'Kanyakumari, India',
'Kerala, India',
'Himachal Pradesh, India',
'Shillong, India',
'Chandigarh, India',
'Dwarka, New Delhi, India',
'Pune, India',
'Indore, India',
'Orissa, India',
'Shimla, India',
'Gujarat, India'
];
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
As we can resolve this issue with setTimeout()
function.
Still we should not geocode known locations every time you load your page as said by @geocodezip
Another alternatives of these are explained very well in the following links:
How To Avoid GoogleMap Geocode Limit!
You have name spaces so you can have globally unique elements. However, 99% of the time this doesn't really matter, but when you put it in the perspective of The Semantic Web, it starts to become important.
For example, you could make an XML mash-up of different schemes just by using the appropriate xmlns
. For example, mash up friend of a friend with vCard, etc.
This could be a problem if you are using a custom 'Settings.xml', with a different <localRepository>
configured in it.
Eclipse will be using the default installation of MAVEN, and will be using the default location for the User to look for the local Maven repository, which on Linux systems would be '/home/${USER}/.m2/'
Eclipse can be easily configured to use the customized 'Settings.xml', by doing the following: Goto -> Window -> Preferences -> Select 'Maven' -> Select 'User Settings'
After this, you could proceed to select your project from the 'Project Explorer', right click, Select 'Maven' > 'Update Project'. Make sure that your project is selected (ticked) in the Window, and click 'OK'.
This should help to resolve the issue, if using custom 'Settings.xml' for Maven.
Hope it helps.
You should use raw_input
to take a string input. then use islower
method of str
object.
s = raw_input('Type a word')
l = []
for c in s.strip():
if c.islower():
print c
l.append(c)
print 'Total number of lowercase letters: %d'%(len(l) + 1)
Just do -
dir(s)
and you will find islower
and other attributes of str
This has been driving me crazy for literally weeks. I found a solution that will work for me that includes:
...but there are a couple of caveats:
The vertical scrollbar is not visible until you scroll all the way to the right. Given that most people have scroll wheels, this was an acceptable sacrifice.
The width of the scrollbar must be known. On my website I set the scrollbar widths (I'm not overly concerned with older, incompatible browsers), so I can then calculate div
and table
widths that adjust based on the scrollbar.
Instead of posting my code here, I'll post a link to the jsFiddle.
According to the docs for func (*Client) Do
:
"An error is returned if caused by client policy (such as CheckRedirect), or if there was an HTTP protocol error. A non-2xx response doesn't cause an error.
When err is nil, resp always contains a non-nil resp.Body."
Then looking at this code:
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
return nil, err
}
I'm guessing that err
is not nil
. You're accessing the .Close()
method on res.Body
before you check for the err
.
The defer
only defers the function call. The field and method are accessed immediately.
So instead, try checking the error immediately.
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
In order of activity, demos/examples available, and simplicity:
Related:
This answer is written to show just how trivial it is to bypass poorly written PHP user-validation code, how (and using what) these attacks work and how to replace the old MySQL functions with a secure prepared statement - and basically, why StackOverflow users (probably with a lot of rep) are barking at new users asking questions to improve their code.
First off, please feel free to create this test mysql database (I have called mine prep):
mysql> create table users(
-> id int(2) primary key auto_increment,
-> userid tinytext,
-> pass tinytext);
Query OK, 0 rows affected (0.05 sec)
mysql> insert into users values(null, 'Fluffeh', 'mypass');
Query OK, 1 row affected (0.04 sec)
mysql> create user 'prepared'@'localhost' identified by 'example';
Query OK, 0 rows affected (0.01 sec)
mysql> grant all privileges on prep.* to 'prepared'@'localhost' with grant option;
Query OK, 0 rows affected (0.00 sec)
With that done, we can move to our PHP code.
Lets assume the following script is the verification process for an admin on a website (simplified but working if you copy and use it for testing):
<?php
if(!empty($_POST['user']))
{
$user=$_POST['user'];
}
else
{
$user='bob';
}
if(!empty($_POST['pass']))
{
$pass=$_POST['pass'];
}
else
{
$pass='bob';
}
$database='prep';
$link=mysql_connect('localhost', 'prepared', 'example');
mysql_select_db($database) or die( "Unable to select database");
$sql="select id, userid, pass from users where userid='$user' and pass='$pass'";
//echo $sql."<br><br>";
$result=mysql_query($sql);
$isAdmin=false;
while ($row = mysql_fetch_assoc($result)) {
echo "My id is ".$row['id']." and my username is ".$row['userid']." and lastly, my password is ".$row['pass']."<br>";
$isAdmin=true;
// We have correctly matched the Username and Password
// Lets give this person full access
}
if($isAdmin)
{
echo "The check passed. We have a verified admin!<br>";
}
else
{
echo "You could not be verified. Please try again...<br>";
}
mysql_close($link);
?>
<form name="exploited" method='post'>
User: <input type='text' name='user'><br>
Pass: <input type='text' name='pass'><br>
<input type='submit'>
</form>
Seems legit enough at first glance.
The user has to enter a login and password, right?
Brilliant, not enter in the following:
user: bob
pass: somePass
and submit it.
The output is as follows:
You could not be verified. Please try again...
Super! Working as expected, now lets try the actual username and password:
user: Fluffeh
pass: mypass
Amazing! Hi-fives all round, the code correctly verified an admin. It's perfect!
Well, not really. Lets say the user is a clever little person. Lets say the person is me.
Enter in the following:
user: bob
pass: n' or 1=1 or 'm=m
And the output is:
The check passed. We have a verified admin!
Congrats, you just allowed me to enter your super-protected admins only section with me entering a false username and a false password. Seriously, if you don't believe me, create the database with the code I provided, and run this PHP code - which at glance REALLY does seem to verify the username and password rather nicely.
So, in answer, THAT IS WHY YOU ARE BEING YELLED AT.
So, lets have a look at what went wrong, and why I just got into your super-admin-only-bat-cave. I took a guess and assumed that you weren't being careful with your inputs and simply passed them to the database directly. I constructed the input in a way tht would CHANGE the query that you were actually running. So, what was it supposed to be, and what did it end up being?
select id, userid, pass from users where userid='$user' and pass='$pass'
That's the query, but when we replace the variables with the actual inputs that we used, we get the following:
select id, userid, pass from users where userid='bob' and pass='n' or 1=1 or 'm=m'
See how I constructed my "password" so that it would first close the single quote around the password, then introduce a completely new comparison? Then just for safety, I added another "string" so that the single quote would get closed as expected in the code we originally had.
However, this isn't about folks yelling at you now, this is about showing you how to make your code more secure.
Okay, so what went wrong, and how can we fix it?
This is a classic SQL injection attack. One of the simplest for that matter. On the scale of attack vectors, this is a toddler attacking a tank - and winning.
So, how do we protect your sacred admin section and make it nice and secure? The first thing to do will be to stop using those really old and deprecated mysql_*
functions. I know, you followed a tutorial you found online and it works, but it's old, it's outdated and in the space of a few minutes, I have just broken past it without so much as breaking a sweat.
Now, you have the better options of using mysqli_ or PDO. I am personally a big fan of PDO, so I will be using PDO in the rest of this answer. There are pro's and con's, but personally I find that the pro's far outweigh the con's. It's portable across multiple database engines - whether you are using MySQL or Oracle or just about bloody anything - just by changing the connection string, it has all the fancy features we want to use and it is nice and clean. I like clean.
Now, lets have a look at that code again, this time written using a PDO object:
<?php
if(!empty($_POST['user']))
{
$user=$_POST['user'];
}
else
{
$user='bob';
}
if(!empty($_POST['pass']))
{
$pass=$_POST['pass'];
}
else
{
$pass='bob';
}
$isAdmin=false;
$database='prep';
$pdo=new PDO ('mysql:host=localhost;dbname=prep', 'prepared', 'example');
$sql="select id, userid, pass from users where userid=:user and pass=:password";
$myPDO = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
if($myPDO->execute(array(':user' => $user, ':password' => $pass)))
{
while($row=$myPDO->fetch(PDO::FETCH_ASSOC))
{
echo "My id is ".$row['id']." and my username is ".$row['userid']." and lastly, my password is ".$row['pass']."<br>";
$isAdmin=true;
// We have correctly matched the Username and Password
// Lets give this person full access
}
}
if($isAdmin)
{
echo "The check passed. We have a verified admin!<br>";
}
else
{
echo "You could not be verified. Please try again...<br>";
}
?>
<form name="exploited" method='post'>
User: <input type='text' name='user'><br>
Pass: <input type='text' name='pass'><br>
<input type='submit'>
</form>
The major differences are that there are no more mysql_*
functions. It's all done via a PDO object, secondly, it is using a prepared statement. Now, what's a prepred statement you ask? It's a way to tell the database ahead of running a query, what the query is that we are going to run. In this case, we tell the database: "Hi, I am going to run a select statement wanting id, userid and pass from the table users where the userid is a variable and the pass is also a variable.".
Then, in the execute statement, we pass the database an array with all the variables that it now expects.
The results are fantastic. Lets try those username and password combinations from before again:
user: bob
pass: somePass
User wasn't verified. Awesome.
How about:
user: Fluffeh
pass: mypass
Oh, I just got a little excited, it worked: The check passed. We have a verified admin!
Now, lets try the data that a clever chap would enter to try to get past our little verification system:
user: bob
pass: n' or 1=1 or 'm=m
This time, we get the following:
You could not be verified. Please try again...
This is why you are being yelled at when posting questions - it's because people can see that your code can be bypassed wihout even trying. Please, do use this question and answer to improve your code, to make it more secure and to use functions that are current.
Lastly, this isn't to say that this is PERFECT code. There are many more things that you could do to improve it, use hashed passwords for example, ensure that when you store sensetive information in the database, you don't store it in plain text, have multiple levels of verification - but really, if you just change your old injection prone code to this, you will be WELL along the way to writing good code - and the fact that you have gotten this far and are still reading gives me a sense of hope that you will not only implement this type of code when writing your websites and applications, but that you might go out and research those other things I just mentioned - and more. Write the best code you can, not the most basic code that barely functions.
That's because the browser doesn't transmit that part to the server, sorry.
I think because C would be seen the C drive on the client pc, it wont let you. And if it could do this, it would be a big security hole.
Have you considered doing this from the layout.xml
? You could set for your ImageView
the ScaleType to android:scaleType="centerCrop"
and set the dimensions of the image in the ImageView
inside the layout.xml
.
Converting AM/PM Time string to 24 Hours Format. Example 9:30 PM to 21:30
function get24HrsFrmAMPM(timeStr) {
if (timeStr && timeStr.indexOf(' ') !== -1 && timeStr.indexOf(':') !== -1) {
var hrs = 0;
var tempAry = timeStr.split(' ');
var hrsMinAry = tempAry[0].split(':');
hrs = parseInt(hrsMinAry[0], 10);
if ((tempAry[1] == 'AM' || tempAry[1] == 'am') && hrs == 12) {
hrs = 0;
} else if ((tempAry[1] == 'PM' || tempAry[1] == 'pm') && hrs != 12) {
hrs += 12;
}
return ('0' + hrs).slice(-2) + ':' + ('0' + parseInt(hrsMinAry[1], 10)).slice(-2);
} else {
return null;
}
}
This relates to Cristóvão D. Sousa's answer, but I couldn't comment yet.
A straight-forward way of using the flush
keyword argument of Python 3 in order to always have unbuffered output is:
import functools
print = functools.partial(print, flush=True)
afterwards, print will always flush the output directly (except flush=False
is given).
Note, (a) that this answers the question only partially as it doesn't redirect all the output. But I guess print
is the most common way for creating output to stdout
/stderr
in python, so these 2 lines cover probably most of the use cases.
Note (b) that it only works in the module/script where you defined it. This can be good when writing a module as it doesn't mess with the sys.stdout
.
Python 2 doesn't provide the flush
argument, but you could emulate a Python 3-type print
function as described here https://stackoverflow.com/a/27991478/3734258 .
While I was starting to learn android development, I had learnt that ProgressDialog
is the way to go. There is the setProgress
method of ProgressDialog
which can be invoked to update the progress level as the file gets downloaded.
The best I have seen in many apps is that they customize this progress dialog's attributes to give a better look and feel to the progress dialog than the stock version. Good to keeping the user engaged with some animation of like frog, elephant or cute cats/puppies. Any animation with in the progress dialog attracts users and they don't feel like being kept waiting for long.
Use the STL
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> userInput;
// Read until end of input.
// Hit control D
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(userInput)
);
// Print in Normal order
std::copy(userInput.begin(),
userInput.end(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
// Print in reverse order:
std::copy(userInput.rbegin(),
userInput.rend(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
// Update for C++11
// Range based for is now a good alternative.
for(auto const& value: userInput)
{
std::cout << value << ",";
}
std::cout << "\n";
}
For Windows users: You can do as RTA said or through command line do this: Navigate to the locaiton of the eclipse executable then run:
eclipse.lnk -clean
First check the name of your executable using the command 'dir' on its path
In your .m file, declare a file global variable:
static int currentID = 1;
then in your init routine, refernce that:
- (id) init
{
self = [super init];
if (self != nil) {
_myID = currentID++; // not thread safe
}
return self;
}
or if it needs to change at some other time (eg in your openConnection method), then increment it there. Remember it is not thread safe as is, you'll need to do syncronization (or better yet, use an atomic add) if there may be any threading issues.
MongoDB's ISODate() is just a helper function that wraps a JavaScript date object and makes it easier to work with ISO date strings.
You can still use all of the same methods as working with a normal JS Date, such as:
ISODate("2012-07-14T01:00:00+01:00").toLocaleTimeString()
// Note that getHours() and getMinutes() do not include leading 0s for single digit #s
ISODate("2012-07-14T01:00:00+01:00").getHours()
ISODate("2012-07-14T01:00:00+01:00").getMinutes()
set "ANDROID_SDK_ROOT" in environment variable, solve my problem.
Depending on how it's being used, it might be necessary and even handy. http://php.net/manual/en/language.operators.logical.php
// "||" has a greater precedence than "or"
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
But in most cases it seems like more of a developer taste thing, like every occurrence of this that I've seen in CodeIgniter framework like @Sarfraz has mentioned.
Another option would be as the return value for the stored procedure (I don't suggest this though, as that's usually best for error values).
I've included it as both when it's inserting a single row in cases where the stored procedure was being consumed by both other SQL procedures and a front-end which couldn't work with OUTPUT parameters (IBATIS in .NET I believe):
CREATE PROCEDURE My_Insert
@col1 VARCHAR(20),
@new_identity INT OUTPUT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO My_Table (col1)
VALUES (@col1)
SELECT @new_identity = SCOPE_IDENTITY()
SELECT @new_identity AS id
RETURN
END
The output parameter is easier to work with in T-SQL when calling from other stored procedures IMO, but some programming languages have poor or no support for output parameters and work better with result sets.
Pandas is great for time series in general, and has direct support for date ranges.
import pandas as pd
daterange = pd.date_range(start_date, end_date)
You can then loop over the daterange to print the date:
for single_date in daterange:
print (single_date.strftime("%Y-%m-%d"))
It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in bdate_range. See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#generating-ranges-of-timestamps
The power of Pandas is really its dataframes, which support vectorized operations (much like numpy) that make operations across large quantities of data very fast and easy.
EDIT: You could also completely skip the for loop and just print it directly, which is easier and more efficient:
print(daterange)
To retrieve path of msbuild 15 (Visual Studio 2017) with batch from registry w/o additional tools:
set regKey=HKLM\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7
set regValue=15.0
for /f "skip=2 tokens=3,*" %%A in ('reg.exe query %regKey% /v %regValue% 2^>nul') do (
set vs17path=%%A %%B
)
set msbuild15path = %vs17path%\MSBuild\15.0\Bin\MSBuild.exe
Better available tools:
dumpbin
from the Visual Studio command prompt:
dumpbin /exports csp.dll
Example of output:
Microsoft (R) COFF/PE Dumper Version 10.00.30319.01
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file csp.dll
File Type: DLL
Section contains the following exports for CSP.dll
00000000 characteristics
3B1D0B77 time date stamp Tue Jun 05 12:40:23 2001
0.00 version
1 ordinal base
25 number of functions
25 number of names
ordinal hint RVA name
1 0 00001470 CPAcquireContext
2 1 000014B0 CPCreateHash
3 2 00001520 CPDecrypt
4 3 000014B0 CPDeriveKey
5 4 00001590 CPDestroyHash
6 5 00001590 CPDestroyKey
7 6 00001560 CPEncrypt
8 7 00001520 CPExportKey
9 8 00001490 CPGenKey
10 9 000015B0 CPGenRandom
11 A 000014D0 CPGetHashParam
12 B 000014D0 CPGetKeyParam
13 C 00001500 CPGetProvParam
14 D 000015C0 CPGetUserKey
15 E 00001580 CPHashData
16 F 000014F0 CPHashSessionKey
17 10 00001540 CPImportKey
18 11 00001590 CPReleaseContext
19 12 00001580 CPSetHashParam
20 13 00001580 CPSetKeyParam
21 14 000014F0 CPSetProvParam
22 15 00001520 CPSignHash
23 16 000015A0 CPVerifySignature
24 17 00001060 DllRegisterServer
25 18 00001000 DllUnregisterServer
Summary
1000 .data
1000 .rdata
1000 .reloc
1000 .rsrc
1000 .text
The route-map express example matches url paths with objects which in turn matches http verbs with functions. This lays the routing out in a tree, which is concise and easy to read. The apps's entities are also written as objects with the functions as enclosed methods.
var express = require('../../lib/express')
, verbose = process.env.NODE_ENV != 'test'
, app = module.exports = express();
app.map = function(a, route){
route = route || '';
for (var key in a) {
switch (typeof a[key]) {
// { '/path': { ... }}
case 'object':
app.map(a[key], route + key);
break;
// get: function(){ ... }
case 'function':
if (verbose) console.log('%s %s', key, route);
app[key](route, a[key]);
break;
}
}
};
var users = {
list: function(req, res){
res.send('user list');
},
get: function(req, res){
res.send('user ' + req.params.uid);
},
del: function(req, res){
res.send('delete users');
}
};
var pets = {
list: function(req, res){
res.send('user ' + req.params.uid + '\'s pets');
},
del: function(req, res){
res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid);
}
};
app.map({
'/users': {
get: users.list,
del: users.del,
'/:uid': {
get: users.get,
'/pets': {
get: pets.list,
'/:pid': {
del: pets.del
}
}
}
}
});
app.listen(3000);
$('.clickable').hover(function(){
$('.selector').stop(true,true).fadeTo( 400 , 0.0, function() {
$('.selector').css('background-image',"url('assets/img/pic2.jpg')");
});
$('.selector').fadeTo( 400 , 1);
},
function(){
$('.selector').stop(false,true).fadeTo( 400 , 0.0, function() {
$('.selector').css('background-image',"url('assets/img/pic.jpg')");
});
$('.selector').fadeTo( 400 , 1);
}
);
for running mutilple js files
#!/bin/bash
cd /root/migrate/
ls -1 *.js | sed 's/.js$//' | while read name; do
start=`date +%s`
mongo localhost:27017/wbars $name.js;
end=`date +%s`
runtime1=$((end-start))
runtime=$(printf '%dh:%dm:%ds\n' $(($runtime1/3600)) $(($secs%3600/60)) $(($secs%60)))
echo @@@@@@@@@@@@@ $runtime $name.js completed @@@@@@@@@@@
echo "$name.js completed"
sync
echo 1 > /proc/sys/vm/drop_caches
echo 2 > /proc/sys/vm/drop_caches
echo 3 > /proc/sys/vm/drop_caches
done
Taken from: http://www.w3.org/Style/Examples/007/units:
The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.
em
is basically CSS property for font sizes.
Autoresize simple Popup Bubble
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="bubble.css" type="text/css" rel="stylesheet" />
<script language="javascript" type="text/javascript" src="jquery.js"></script>
<script language="javascript" type="text/javascript" src="bubble.js"></script>
</head>
<body>
<br/><br/>
<div class="bubbleInfo">
<div class="bubble" title="Text 1">Set cursor</div>
</div>
<br/><br/><br/><br/>
<div class="bubbleInfo">
<div class="bubble" title="Text 2">Set cursor</div>
</div>
</body>
</html>
bubble.js
$(function () {
var i = 0;
var z=1;
do{
title = $('.bubble:eq('+i+')').attr('title');
if(!title){
z=0;
} else {
$('.bubble:eq('+i+')').after('<table style="opacity: 0; top: -50px; left: -33px; display: none;" id="dpop" class="popup"><tbody><tr><td id="topleft" class="corner"></td><td class="top"></td><td id="topright" class="corner"></td></tr><tr><td class="left"></td><td>'+title+'</td><td class="right"></td></tr><tr><td class="corner" id="bottomleft"></td><td class="bottom"><img src="bubble/bubble-tail.png" height="25px" width="30px" /></td><td id="bottomright" class="corner"></td></tr></tbody></table>');
$('.bubble:eq('+i+')').removeAttr('title');
}
i++;
}while(z>0)
$('.bubbleInfo').each(function () {
var distance = 10;
var time = 250;
var hideDelay = 500;
var hideDelayTimer = null;
var beingShown = false;
var shown = false;
var trigger = $('.bubble', this);
var info = $('.popup', this).css('opacity', 0);
$([trigger.get(0), info.get(0)]).mouseover(function () {
if (hideDelayTimer) clearTimeout(hideDelayTimer);
if (beingShown || shown) {
// don't trigger the animation again
return;
} else {
// reset position of info box
beingShown = true;
info.css({
top: -40,
left: 10,
display: 'block'
}).animate({
top: '-=' + distance + 'px',
opacity: 1
}, time, 'swing', function() {
beingShown = false;
shown = true;
});
}
return false;
}).mouseout(function () {
if (hideDelayTimer) clearTimeout(hideDelayTimer);
hideDelayTimer = setTimeout(function () {
hideDelayTimer = null;
info.animate({
top: '-=' + distance + 'px',
opacity: 0
}, time, 'swing', function () {
shown = false;
info.css('display', 'none');
});
}, hideDelay);
return false;
});
});
});
bubble.css
/* Booble */
.bubbleInfo {
position: relative;
width: 500px;
}
.bubble {
}
.popup {
position: absolute;
display: none;
z-index: 50;
border-collapse: collapse;
font-size: .8em;
}
.popup td.corner {
height: 13px;
width: 15px;
}
.popup td#topleft {
background-image: url(bubble/bubble-1.png);
}
.popup td.top {
background-image: url(bubble/bubble-2.png);
}
.popup td#topright {
background-image: url(bubble/bubble-3.png);
}
.popup td.left {
background-image: url(bubble/bubble-4.png);
}
.popup td.right {
background-image: url(bubble/bubble-5.png);
}
.popup td#bottomleft {
background-image: url(bubble/bubble-6.png);
}
.popup td.bottom {
background-image: url(bubble/bubble-7.png);
text-align: center;
}
.popup td.bottom img {
display: block;
margin: 0 auto;
}
.popup td#bottomright {
background-image: url(bubble/bubble-8.png);
}
Use flush when you need to write, for example to get a primary key ID from an autoincrementing counter.
john=Person(name='John Smith', parent=None)
session.add(john)
session.flush()
son=Person(name='Bill Smith', parent=john.id)
Without flushing, john would never get an ID from the DB and so couldn't represent the parent/child relationship in code.
Like others have said, without commit()
none of this will be permanently persisted to DB.
buildScript {
...
dependencies {
...
classpath 'com.android.tools.build:gradle:4.0.0-rc01'
}
}
...
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
Some libraries require the updated gradle. Such as:
androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines"
GL
They are not the same. The first one replaces the HTML without creating another jQuery object first. The second creates an additional jQuery wrapper for the second div, then appends it to the first.
One jQuery Wrapper (per example):
$("#myDiv").html('<div id="mySecondDiv"></div>');
$("#myDiv").append('<div id="mySecondDiv"></div>');
Two jQuery Wrappers (per example):
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').html(mySecondDiv);
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').append(mySecondDiv);
You have a few different use cases going on. If you want to replace the content, .html
is a great call since its the equivalent of innerHTML = "..."
. However, if you just want to append content, the extra $()
wrapper set is unneeded.
Only use two wrappers if you need to manipulate the added div
later on. Even in that case, you still might only need to use one:
var mySecondDiv = $("<div id='mySecondDiv'></div>").appendTo("#myDiv");
// other code here
mySecondDiv.hide();
Try This
var player:AVPlayer!
var avPlayerLayer:AVPlayerLayer = AVPlayerLayer(player: player)
avPlayerLayer.frame = CGRectMake(your frame)
self.view.layer .addSublayer(avPlayerLayer)
var steamingURL:NSURL = NSURL(string:playerURL)
player = AVPlayer(URL: steamingURL)
player.play()
import re
re.search(r"(?<=AAA).*?(?=ZZZ)", your_text).group(0)
The above as-is will fail with an AttributeError
if there are no "AAA" and "ZZZ" in your_text
your_text.partition("AAA")[2].partition("ZZZ")[0]
The above will return an empty string if either "AAA" or "ZZZ" don't exist in your_text
.
PS Python Challenge?
Looking around for an API Level 5 solution using ContactsContract API you could slightly modify the code above with the following:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
And then in onActivityResult use the column name:
ContactsContract.Contacts.DISPLAY_NAME
Make a Facebook app with these simple steps I have written below:
If you need Unicode support in the lower case function see this question: Light C Unicode Library
One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource
and supply it with StringReader
.
String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());
If you want to discard modifications you made to the file, you can do:
git reset first_Name.txt
git checkout first_Name.txt
<font size=1>- font size 1</font><br>
<span style="font-size:0.63em">- font size: 0.63em</span><br>
<font size=2>- font size 2</font><br>
<span style="font-size: 0.82em">- font size: 0.82em</span><br>
<font size=3>- font size 3</font><br>
<span style="font-size: 1.0em">- font size: 1.0em</span><br>
<font size=4>- font size 4</font><br>
<span style="font-size: 1.13em">- font size: 1.13em</span><br>
<font size=5>- font size 5</font><br>
<span style="font-size: 1.5em">- font size: 1.5em</span><br>
<font size=6>- font size 6</font><br>
<span style="font-size: 2em">- font size: 2em</span><br>
<font size=7>- font size 7</font><br>
<span style="font-size: 3em">- font size: 3em</span><br>
Check your environment variables.
In my case I had JAVA_HOME set in the System variables as well as in my User Account variables and the latter was set to a wrong version of Java. I also had the same problem with the Path variable.
After deleting JAVA_HOME from my User Account variables and removing the wrong path from the Path variable it worked correctly.
This is the most complicated scenario I can imagine: I have a PDF file created with Ilustrator and modified with Acrobat to have AcroFields (AcroForm) that I'm going to fill with data with this Java code, the result of that PDF file with the data in the fields is modified adding a Document.
Actually in this case I'm dynamically generating a background that is added to a PDF that is also dynamically generated with a Document with an unknown amount of data or pages.
I'm using JBoss and this code is inside a JSP file (should work in any JSP webserver).
Note: if you are using IExplorer you must submit a HTTP form with POST method to be able to download the file. If not you are going to see the PDF code in the screen. This does not happen in Chrome or Firefox.
<%@ page import="java.io.*, com.lowagie.text.*, com.lowagie.text.pdf.*" %><%
response.setContentType("application/download");
response.setHeader("Content-disposition","attachment;filename=listaPrecios.pdf" );
// -------- FIRST THE PDF WITH THE INFO ----------
String str = "";
// lots of words
for(int i = 0; i < 800; i++) str += "Hello" + i + " ";
// the document
Document doc = new Document( PageSize.A4, 25, 25, 200, 70 );
ByteArrayOutputStream streamDoc = new ByteArrayOutputStream();
PdfWriter.getInstance( doc, streamDoc );
// lets start filling with info
doc.open();
doc.add(new Paragraph(str));
doc.close();
// the beauty of this is the PDF will have all the pages it needs
PdfReader frente = new PdfReader(streamDoc.toByteArray());
PdfStamper stamperDoc = new PdfStamper( frente, response.getOutputStream());
// -------- THE BACKGROUND PDF FILE -------
// in JBoss the file has to be in webinf/classes to be readed this way
PdfReader fondo = new PdfReader("listaPrecios.pdf");
ByteArrayOutputStream streamFondo = new ByteArrayOutputStream();
PdfStamper stamperFondo = new PdfStamper( fondo, streamFondo);
// the acroform
AcroFields form = stamperFondo.getAcroFields();
// the fields
form.setField("nombre","Avicultura");
form.setField("descripcion","Esto describe para que sirve la lista ");
stamperFondo.setFormFlattening(true);
stamperFondo.close();
// our background is ready
PdfReader fondoEstampado = new PdfReader( streamFondo.toByteArray() );
// ---- ADDING THE BACKGROUND TO EACH DATA PAGE ---------
PdfImportedPage pagina = stamperDoc.getImportedPage(fondoEstampado,1);
int n = frente.getNumberOfPages();
PdfContentByte background;
for (int i = 1; i <= n; i++) {
background = stamperDoc.getUnderContent(i);
background.addTemplate(pagina, 0, 0);
}
// after this everithing will be written in response.getOutputStream()
stamperDoc.close();
%>
There is another solution much simpler, and solves your problem. It depends the amount of text you want to add.
// read the file
PdfReader fondo = new PdfReader("listaPrecios.pdf");
PdfStamper stamper = new PdfStamper( fondo, response.getOutputStream());
PdfContentByte content = stamper.getOverContent(1);
// add text
ColumnText ct = new ColumnText( content );
// this are the coordinates where you want to add text
// if the text does not fit inside it will be cropped
ct.setSimpleColumn(50,500,500,50);
ct.setText(new Phrase(str, titulo1));
ct.go();
Use the <sup></sup>
tag (<sub></sub>
is the equivalent for subscripts). See this gist for an example.
After validation and before INSERT check if username already exists, using mysqli(procedural). This works:
//check if username already exists
include 'phpscript/connect.php'; //connect to your database
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$usernameErr = "username already taken"; //takes'em back to form
} else { // go on to INSERT new record
function omit(obj, key) {
const {[key]:ignore, ...rest} = obj;
return rest;
}
You can use ES6 spread operators like this. And to remove your key simply call
const newJson = omit(myjsonobj, "otherIndustry");
Its always better if you maintain pure function when you deal with type=object
in javascript.
When executing a script in a remote server. Mongo will add its own logging output, which we might want to omit from our file.
--quiet
option will only disable connection related logs. Not all mongo logs. In such case we might need to filter out unneeded lines manually. A Windows based example:
mongo dbname --username userName --password password --host replicaset/ip:port --quiet printDataToCsv.js | findstr /v "NETWORK" > data.csv
This will pipe the script output and use findstr
to filter out any lines, which have NETWORK string in them. More information on findstr: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/findstr
A Linux version of this would use grep
.
This below code just show the very basic use of delegate concept .. you name the variable and class as per your requirement.
First you need to declare a protocol:
Let's call it MyFirstControllerDelegate.h
@protocol MyFirstControllerDelegate
- (void) FunctionOne: (MyDataOne*) dataOne;
- (void) FunctionTwo: (MyDatatwo*) dataTwo;
@end
Import MyFirstControllerDelegate.h file and confirm your FirstController with protocol MyFirstControllerDelegate
#import "MyFirstControllerDelegate.h"
@interface FirstController : UIViewController<MyFirstControllerDelegate>
{
}
@end
In the implementation file, you need to implement both functions of protocol:
@implementation FirstController
- (void) FunctionOne: (MyDataOne*) dataOne
{
//Put your finction code here
}
- (void) FunctionTwo: (MyDatatwo*) dataTwo
{
//Put your finction code here
}
//Call below function from your code
-(void) CreateSecondController
{
SecondController *mySecondController = [SecondController alloc] initWithSomeData:.];
//..... push second controller into navigation stack
mySecondController.delegate = self ;
[mySecondController release];
}
@end
in your SecondController:
@interface SecondController:<UIViewController>
{
id <MyFirstControllerDelegate> delegate;
}
@property (nonatomic,assign) id <MyFirstControllerDelegate> delegate;
@end
In the implementation file of SecondController.
@implementation SecondController
@synthesize delegate;
//Call below two function on self.
-(void) SendOneDataToFirstController
{
[delegate FunctionOne:myDataOne];
}
-(void) SendSecondDataToFirstController
{
[delegate FunctionTwo:myDataSecond];
}
@end
Here is the wiki article on delegate.
The trouble with using dates as x-values, is that if you want a bar chart like in your second picture, they are going to be wrong. You should either use a stacked bar chart (colours on top of each other) or group by date (a "fake" date on the x-axis, basically just grouping the data points).
import numpy as np
import matplotlib.pyplot as plt
N = 3
ind = np.arange(N) # the x locations for the groups
width = 0.27 # the width of the bars
fig = plt.figure()
ax = fig.add_subplot(111)
yvals = [4, 9, 2]
rects1 = ax.bar(ind, yvals, width, color='r')
zvals = [1,2,3]
rects2 = ax.bar(ind+width, zvals, width, color='g')
kvals = [11,12,13]
rects3 = ax.bar(ind+width*2, kvals, width, color='b')
ax.set_ylabel('Scores')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('2011-Jan-4', '2011-Jan-5', '2011-Jan-6') )
ax.legend( (rects1[0], rects2[0], rects3[0]), ('y', 'z', 'k') )
def autolabel(rects):
for rect in rects:
h = rect.get_height()
ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
plt.show()
You can LEFT JOIN the two tables. If there is no corresponding row in the second table, the values will be NULL.
SELECT id FROM partmaster LEFT JOIN product_details ON (...) WHERE product_details.part_num IS NULL
To enable production mode in angular 6.X.X Just go to environment file
Like this path
Your path: project>\src\environments\environment.ts
Change production: false
from :
export const environment = {
production: false
};
To
export const environment = {
production: true
};
This should do the trick,
npm install -g typescript
You could just change the shebang line. I do this all the time on new systems.
If you want pip
to install to a current version of Python installed just update the shebang line to the correct version of pythons path.
For example, to change pip (not pip3) to install to Python 3:
#!/usr/bin/python
To:
#!/usr/bin/python3
Any module you install using pip
should install to Python not Python.
Or you could just change the path.
Ok here is what I do
sys.argv is always what you type into the terminal or use as the file path when executing it with python.exe or pythonw.exe
For example you can run the file text.py several ways, they each give you a different answer they always give you the path that python was typed.
C:\Documents and Settings\Admin>python test.py
sys.argv[0]: test.py
C:\Documents and Settings\Admin>python "C:\Documents and Settings\Admin\test.py"
sys.argv[0]: C:\Documents and Settings\Admin\test.py
Ok so know you can get the file name, great big deal, now to get the application directory you can know use os.path, specifically abspath and dirname
import sys, os
print os.path.dirname(os.path.abspath(sys.argv[0]))
That will output this:
C:\Documents and Settings\Admin\
it will always output this no matter if you type python test.py or python "C:\Documents and Settings\Admin\test.py"
The problem with using __file__ Consider these two files test.py
import sys
import os
def paths():
print "__file__: %s" % __file__
print "sys.argv: %s" % sys.argv[0]
a_f = os.path.abspath(__file__)
a_s = os.path.abspath(sys.argv[0])
print "abs __file__: %s" % a_f
print "abs sys.argv: %s" % a_s
if __name__ == "__main__":
paths()
import_test.py
import test
import sys
test.paths()
print "--------"
print __file__
print sys.argv[0]
Output of "python test.py"
C:\Documents and Settings\Admin>python test.py
__file__: test.py
sys.argv: test.py
abs __file__: C:\Documents and Settings\Admin\test.py
abs sys.argv: C:\Documents and Settings\Admin\test.py
Output of "python test_import.py"
C:\Documents and Settings\Admin>python test_import.py
__file__: C:\Documents and Settings\Admin\test.pyc
sys.argv: test_import.py
abs __file__: C:\Documents and Settings\Admin\test.pyc
abs sys.argv: C:\Documents and Settings\Admin\test_import.py
--------
test_import.py
test_import.py
So as you can see file gives you always the python file it is being run from, where as sys.argv[0] gives you the file that you ran from the interpreter always. Depending on your needs you will need to choose which one best fits your needs.
There might be more than just one php.ini file. For example, when using WAMP there are 2 php.ini files in following directories:
C:\wamp\bin\apache\apache2.4.9\bin
C:\wamp\bin\php\php5.5.12
You need to edit the first one.
For running on stock iOS devices, make your app an audio player/recorder or a VOIP app, a legitimate one for submitting to the App store, or a fake one if only for your own use.
Even this won't make an app "fully operational" whatever that is, but restricted to limited APIs.
As said by Scott Chamberlain(and several others), Tuples work best if you don't mind having immutable(ie read-only) objects.
If, like suggested by David, you want to reference the int by the string value, for example, you should use a dictionary
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("string", 1);
Console.WriteLine(d["string"]);//prints 1
If, however, you want to store your elements mutably in a list, and don't want to use a dictionary-style referencing system, then your best bet(ie only real solution right now) would be to use KeyValuePair, which is essentially std::pair for C#:
var kvp=new KeyValuePair<int, string>(2, "a");
//kvp.Key=2 and a.Value="a";
kvp.Key = 3;//both key and
kvp.Value = "b";//value are mutable
Of course, this is stackable, so if you need a larger tuple(like if you needed 4 elements) you just stack it. Granted this gets ugly really fast:
var quad=new KeyValuePair<KeyValuePair<int,string>, KeyValuePair<int,string>>
(new KeyValuePair<int,string>(3,"a"),
new KeyValuePair<int,string>(4,"b"));
//quad.Key.Key=3
So obviously if you were to do this, you should probably also define an auxiliary function.
My advice is that if your tuple contains more than 2 elements, define your own class. You could use a typedef-esque using statement like :
using quad = KeyValuePair<KeyValuePair<int,string>, KeyValuePair<int,string>>;
but that doesn't make your instantiations any easier. You'd probably spend a lot less time writing template parameters and more time on the non-boilerplate code if you go with a user-defined class when working with tuples of more than 2 elements
Yes, just delete the branch by running git push origin :branchname
. To fix a new issue later, branch off from master again.
Select the System.Web.Mvc assembly in the "References" folder in the solution explorer. Bring up the properties window (F4) and check the Version
For handling errors from ajax calls on the client side, you assign a function to the error
option of the ajax call.
To set a default globally, you can use the function described here: http://api.jquery.com/jQuery.ajaxSetup.
ContextMenuStrip
CellContextMenuStripNeeded
e.ColumnIndex
, e.RowIndex
.I believe that e.RowIndex
is what you are asking for.
Suggestion: when user causes your event CellContextMenuStripNeeded
to fire, use e.RowIndex
to get data from your grid, such as the ID. Store the ID as the menu event's tag item.
Now, when user actually clicks your menu item, use the Sender property to fetch the tag. Use the tag, containing your ID, to perform the action you need.
Yes, there are a couple of differences, though in practical terms they're not usually big ones.
There's a fourth way, and as of ES2015 (ES6) there's two more. I've added the fourth way at the end, but inserted the ES2015 ways after #1 (you'll see why), so we have:
var a = 0; // 1
let a = 0; // 1.1 (new with ES2015)
const a = 0; // 1.2 (new with ES2015)
a = 0; // 2
window.a = 0; // 3
this.a = 0; // 4
#1 var a = 0;
This creates a global variable which is also a property of the global object, which we access as window
on browsers (or via this
a global scope, in non-strict code). Unlike some other properties, the property cannot be removed via delete
.
In specification terms, it creates an identifier binding on the object Environment Record for the global environment. That makes it a property of the global object because the global object is where identifier bindings for the global environment's object Environment Record are held. This is why the property is non-deletable: It's not just a simple property, it's an identifier binding.
The binding (variable) is defined before the first line of code runs (see "When var
happens" below).
Note that on IE8 and earlier, the property created on window
is not enumerable (doesn't show up in for..in
statements). In IE9, Chrome, Firefox, and Opera, it's enumerable.
#1.1 let a = 0;
This creates a global variable which is not a property of the global object. This is a new thing as of ES2015.
In specification terms, it creates an identifier binding on the declarative Environment Record for the global environment rather than the object Environment Record. The global environment is unique in having a split Environment Record, one for all the old stuff that goes on the global object (the object Environment Record) and another for all the new stuff (let
, const
, and the functions created by class
) that don't go on the global object.
The binding is created before any step-by-step code in its enclosing block is executed (in this case, before any global code runs), but it's not accessible in any way until the step-by-step execution reaches the let
statement. Once execution reaches the let
statement, the variable is accessible. (See "When let
and const
happen" below.)
#1.2 const a = 0;
Creates a global constant, which is not a property of the global object.
const
is exactly like let
except that you must provide an initializer (the = value
part), and you cannot change the value of the constant once it's created. Under the covers, it's exactly like let
but with a flag on the identifier binding saying its value cannot be changed. Using const
does three things for you:
#2 a = 0;
This creates a property on the global object implicitly. As it's a normal property, you can delete it. I'd recommend not doing this, it can be unclear to anyone reading your code later. If you use ES5's strict mode, doing this (assigning to a non-existent variable) is an error. It's one of several reasons to use strict mode.
And interestingly, again on IE8 and earlier, the property created not enumerable (doesn't show up in for..in
statements). That's odd, particularly given #3 below.
#3 window.a = 0;
This creates a property on the global object explicitly, using the window
global that refers to the global object (on browsers; some non-browser environments have an equivalent global variable, such as global
on NodeJS). As it's a normal property, you can delete it.
This property is enumerable, on IE8 and earlier, and on every other browser I've tried.
#4 this.a = 0;
Exactly like #3, except we're referencing the global object through this
instead of the global window
. This won't work in strict mode, though, because in strict mode global code, this
doesn't have a reference to the global object (it has the value undefined
instead).
What do I mean by "deleting" or "removing" a
? Exactly that: Removing the property (entirely) via the delete
keyword:
window.a = 0;
display("'a' in window? " + ('a' in window)); // displays "true"
delete window.a;
display("'a' in window? " + ('a' in window)); // displays "false"
delete
completely removes a property from an object. You can't do that with properties added to window
indirectly via var
, the delete
is either silently ignored or throws an exception (depending on the JavaScript implementation and whether you're in strict mode).
Warning: IE8 again (and presumably earlier, and IE9-IE11 in the broken "compatibility" mode): It won't let you delete properties of the window
object, even when you should be allowed to. Worse, it throws an exception when you try (try this experiment in IE8 and in other browsers). So when deleting from the window
object, you have to be defensive:
try {
delete window.prop;
}
catch (e) {
window.prop = undefined;
}
That tries to delete the property, and if an exception is thrown it does the next best thing and sets the property to undefined
.
This only applies to the window
object, and only (as far as I know) to IE8 and earlier (or IE9-IE11 in the broken "compatibility" mode). Other browsers are fine with deleting window
properties, subject to the rules above.
var
happensThe variables defined via the var
statement are created before any step-by-step code in the execution context is run, and so the property exists well before the var
statement.
This can be confusing, so let's take a look:
display("foo in window? " + ('foo' in window)); // displays "true"
display("window.foo = " + window.foo); // displays "undefined"
display("bar in window? " + ('bar' in window)); // displays "false"
display("window.bar = " + window.bar); // displays "undefined"
var foo = "f";
bar = "b";
display("foo in window? " + ('foo' in window)); // displays "true"
display("window.foo = " + window.foo); // displays "f"
display("bar in window? " + ('bar' in window)); // displays "true"
display("window.bar = " + window.bar); // displays "b"
Live example:
display("foo in window? " + ('foo' in window)); // displays "true"_x000D_
display("window.foo = " + window.foo); // displays "undefined"_x000D_
display("bar in window? " + ('bar' in window)); // displays "false"_x000D_
display("window.bar = " + window.bar); // displays "undefined"_x000D_
var foo = "f";_x000D_
bar = "b";_x000D_
display("foo in window? " + ('foo' in window)); // displays "true"_x000D_
display("window.foo = " + window.foo); // displays "f"_x000D_
display("bar in window? " + ('bar' in window)); // displays "true"_x000D_
display("window.bar = " + window.bar); // displays "b"_x000D_
_x000D_
function display(msg) {_x000D_
var p = document.createElement('p');_x000D_
p.innerHTML = msg;_x000D_
document.body.appendChild(p);_x000D_
}
_x000D_
As you can see, the symbol foo
is defined before the first line, but the symbol bar
isn't. Where the var foo = "f";
statement is, there are really two things: defining the symbol, which happens before the first line of code is run; and doing an assignment to that symbol, which happens where the line is in the step-by-step flow. This is known as "var
hoisting" because the var foo
part is moved ("hoisted") to the top of the scope, but the foo = "f"
part is left in its original location. (See Poor misunderstood var
on my anemic little blog.)
let
and const
happenlet
and const
are different from var
in a couple of ways. The way that's relevant to the question is that although the binding they define is created before any step-by-step code runs, it's not accessible until the let
or const
statement is reached.
So while this runs:
display(a); // undefined
var a = 0;
display(a); // 0
This throws an error:
display(a); // ReferenceError: a is not defined
let a = 0;
display(a);
The other two ways that let
and const
differ from var
, which aren't really relevant to the question, are:
var
always applies to the entire execution context (throughout global code, or throughout function code in the function where it appears), but let
and const
apply only within the block where they appear. That is, var
has function (or global) scope, but let
and const
have block scope.
Repeating var a
in the same context is harmless, but if you have let a
(or const a
), having another let a
or a const a
or a var a
is a syntax error.
Here's an example demonstrating that let
and const
take effect immediately in their block before any code within that block runs, but aren't accessible until the let
or const
statement:
var a = 0;
console.log(a);
if (true)
{
console.log(a); // ReferenceError: a is not defined
let a = 1;
console.log(a);
}
Note that the second console.log
fails, instead of accessing the a
from outside the block.
window
)The window
object gets very, very cluttered with properties. Whenever possible, strongly recommend not adding to the mess. Instead, wrap up your symbols in a little package and export at most one symbol to the window
object. (I frequently don't export any symbols to the window
object.) You can use a function to contain all of your code in order to contain your symbols, and that function can be anonymous if you like:
(function() {
var a = 0; // `a` is NOT a property of `window` now
function foo() {
alert(a); // Alerts "0", because `foo` can access `a`
}
})();
In that example, we define a function and have it executed right away (the ()
at the end).
A function used in this way is frequently called a scoping function. Functions defined within the scoping function can access variables defined in the scoping function because they're closures over that data (see: Closures are not complicated on my anemic little blog).
To get a copy in a file on the local file-system, this rickety utility from the Windows start button menu worked: "C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\DTSWizard.exe"
Based on the answers above, here is how to create a brand new keystore for your java based web server, out of an independently created Comodo cert and private key using keytool (requires JDK 1.6+)
Issue this command and at the password prompt enter somepass - 'server.crt' is your server's cert and 'server.key' is the private key you used for issuing the CSR:
openssl pkcs12 -export -in server.crt -inkey server.key -out server.p12 -name www.yourdomain.com -CAfile AddTrustExternalCARoot.crt -caname "AddTrust External CA Root"
Then use keytool to convert the p12 keystore into a jks keystore:
keytool -importkeystore -deststorepass somepass -destkeypass somepass -destkeystore keystore.jks -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass somepass
Then import the other two root/intermediate certs you received from Comodo:
Import COMODORSAAddTrustCA.crt:
keytool -import -trustcacerts -alias cert1 -file COMODORSAAddTrustCA.crt -keystore keystore.jks
Import COMODORSADomainValidationSecureServerCA.crt:
keytool -import -trustcacerts -alias cert2 -file COMODORSADomainValidationSecureServerCA.crt -keystore keystore.jks
Using case
#!/bin/bash
fun1 () {
echo "run function1"
[[ "$@" ]] && echo "options: $@"
}
fun2 () {
echo "run function2"
[[ "$@" ]] && echo "options: $@"
}
case $1 in
fun1) "$@"; exit;;
fun2) "$@"; exit;;
esac
fun1
fun2
This script will run functions fun1 and fun2 but if you start it with option fun1 or fun2 it'll only run given function with args(if provided) and exit. Usage
$ ./test
run function1
run function2
$ ./test fun2 a b c
run function2
options: a b c
As people pointed out string handling improved much. So you may want to learn how to use the C++ string library instead of C-style strings. However here is a solution in pure C
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void appendToHello(const char *s) {
const char *const hello = "hello ";
const size_t sLength = strlen(s);
const size_t helloLength = strlen(hello);
const size_t totalLength = sLength + helloLength;
char *const strBuf = malloc(totalLength + 1);
if (strBuf == NULL) {
fprintf(stderr, "malloc failed\n");
exit(EXIT_FAILURE);
}
strcpy(strBuf, hello);
strcpy(strBuf + helloLength, s);
puts(strBuf);
free(strBuf);
}
int main (void) {
appendToHello("blah blah");
return 0;
}
I am not sure whether it is correct/safe but right now I could not find a better way to do this in ANSI C.
platform.js seems like a good one file library to do this.
Usage example:
// on IE10 x86 platform preview running in IE7 compatibility mode on Windows 7 64 bit edition
platform.name; // 'IE'
platform.version; // '10.0'
platform.layout; // 'Trident'
platform.os; // 'Windows Server 2008 R2 / 7 x64'
platform.description; // 'IE 10.0 x86 (platform preview; running in IE 7 mode) on Windows Server 2008 R2 / 7 x64'
// or on an iPad
platform.name; // 'Safari'
platform.version; // '5.1'
platform.product; // 'iPad'
platform.manufacturer; // 'Apple'
platform.layout; // 'WebKit'
platform.os; // 'iOS 5.0'
platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)'
// or parsing a given UA string
var info = platform.parse('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7.2; en; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 11.52');
info.name; // 'Opera'
info.version; // '11.52'
info.layout; // 'Presto'
info.os; // 'Mac OS X 10.7.2'
info.description; // 'Opera 11.52 (identifying as Firefox 4.0) on Mac OS X 10.7.2'
I think an elegant way of doing this is by defining your functions in a hash object. Then you can have a reference to those functions from the hash using the string. e.g.
var customObject = {
customFunction: function(param){...}
};
Then you can call:
customObject['customFunction'](param);
Where customFunction will be a string matching a function defined in your object.
UPDATE
It seems that this answer was helpful for many fellow coders out there so here goes an updated version.
With ES6 you can additionally use Computed Property Names which will allow you to avoid magic strings.
const FunctionNames = Object.freeze({
FirstFunction: "firstFunction",
SecondFunction: "secondFunction"
});
...
var customObject = {
[FunctionNames.FirstFunction]: function(param){...},
[FunctionNames.SecondFunction]: function(param){...}
};
...
customObject[FunctionNames.FirstFunction](param);
_x000D_
I also tried this a while ago (Launch iPhone Application with Identifier), but there definitely is no DOCUMENTED way to do this. :)
I'm maybe a little bit late but I'm currently trying to develop a program which can brute force a password protected zip archive. First I tried all commands I found in the internet to extract it through cmd... But it never worked....Every time I tried it, the cmd output said, that the key was wrong but it was right. I think they just disenabled this function in a current version.
What I've done to Solve the problem was to download an older 7zip version(4.?) and to use this for extracting through cmd.
This is the command: "C:/Program Files (86)/old7-zip/7z.exe" x -pKey "C:/YOURE_ZIP_PATH"
The first value("C:/Program Files (86)/old7-zip/7z.exe") has to be the path where you have installed the old 7zip to. The x is for extract and the -p For you're password. Make sure you put your password without any spaces behind the -p! The last value is your zip archive to extract. The destination where the zip is extracted to will be the current path of cmd. You can change it with: cd YOURE_PATH
Now I let execute this command through java with my password trys. Then I check the error output stream of cmd and if it is null-> then the password is right!
First create a DataGridTemplateColumn
to contain the button:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="ShowHideDetails">Details</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
When the button is clicked, update the containing DataGridRow
's DetailsVisibility
:
void ShowHideDetails(object sender, RoutedEventArgs e)
{
for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
if (vis is DataGridRow)
{
var row = (DataGridRow)vis;
row.DetailsVisibility =
row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
break;
}
}
I use them all the time. The only thing I worry about is giving away IP in log files. If your function names are really good you might be making a trade secret easier to uncover. It's sort of like shipping with debug symbols, only more difficult to find things. In 99.999% of the cases nothing bad will come of it.
$(element).click(function(){
window.close();
});
Note: you can not close any window that you didn't opened with window.open
. Directly invoking window.close()
will ask user with a dialogue box.
For SublimeText 3 on Mac:
# .jshintrc
{
"esversion": 6
}
// SublimeLinter Settings - User
{
"linters": {
"jshint": {
"args": ["--config", "/Users/[your_username]/.jshintrc"]
}
}
}
I use Visual Studio 2013 Professional.
You also place the cursor for choosing a property. Use menu Edit → Refactor → Encapsulate Field...
Other information:
Since C# 3.0 (November 19th 2007), we can use auto-implemented properties (this is merely syntactic sugar).
And
private int productID;
public int ProductID
{
get { return productID; }
set { productID = value; }
}
becomes
public int ProductID { get; set; }