Split and join C# string
Well, here is my "answer". It uses the fact that String.Split can be told hold many items it should split to (which I found lacking in the other answers):
string theString = "Some Very Large String Here";
var array = theString.Split(new [] { ' ' }, 2); // return at most 2 parts
// note: be sure to check it's not an empty array
string firstElem = array[0];
// note: be sure to check length first
string restOfArray = array[1];
This is very similar to the Substring
method, just by a different means.
jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON
According to the state machine diagram on the JSON website, only escaped double-quote characters are allowed, not single-quotes. Single quote characters do not need to be escaped:
Update - More information for those that are interested:
Douglas Crockford does not specifically say why the JSON specification does not allow escaped single quotes within strings. However, during his discussion of JSON in Appendix E of JavaScript: The Good Parts, he writes:
JSON's design goals were to be minimal, portable, textual, and a subset of JavaScript. The less we need to agree on in order to interoperate, the more easily we can interoperate.
So perhaps he decided to only allow strings to be defined using double-quotes since this is one less rule that all JSON implementations must agree on. As a result, it is impossible for a single quote character within a string to accidentally terminate the string, because by definition a string can only be terminated by a double-quote character. Hence there is no need to allow escaping of a single quote character in the formal specification.
Digging a little bit deeper, Crockford's
org.json implementation of JSON for Java is more permissible and
does allow single quote characters:
The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more forgiving in the texts they will accept:
...
- Strings may be quoted with ' (single quote).
This is confirmed by the JSONTokener source code. The nextString
method accepts escaped single quote characters and treats them just like double-quote characters:
public String nextString(char quote) throws JSONException {
char c;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
switch (c) {
...
case '\\':
c = this.next();
switch (c) {
...
case '"':
case '\'':
case '\\':
case '/':
sb.append(c);
break;
...
At the top of the method is an informative comment:
The formal JSON format does not allow strings in single quotes, but an implementation is allowed to accept them.
So some implementations will accept single quotes - but you should not rely on this. Many popular implementations are quite restrictive in this regard and will reject JSON that contains single quoted strings and/or escaped single quotes.
Finally to tie this back to the original question, jQuery.parseJSON
first attempts to use the browser's native JSON parser or a loaded library such as json2.js where applicable (which on a side note is the library the jQuery logic is based on if JSON
is not defined). Thus jQuery can only be as permissive as that underlying implementation:
parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
jQuery.error( "Invalid JSON: " + data );
},
As far as I know these implementations only adhere to the official JSON specification and do not accept single quotes, hence neither does jQuery.
Request Permission for Camera and Library in iOS 10 - Info.plist
Swift 5
The easiest way to add permissions without having to do it programatically, is to open your info.plist file and select the + next to Information Property list. Scroll through the drop down list to the Privacy options and select Privacy Camera Usage Description for accessing camera, or Privacy Photo Library Usage Description for accessing the Photo Library. Fill in the String value on the right after you've made your selection, to include the text you would like displayed to your user when the alert pop up asks for permissions.
Converting Float to Dollars and Cents
you said that:
`mony = float(1234.5)
print(money) #output is 1234.5
'${:,.2f}'.format(money)
print(money)
did not work....
Have you coded exactly that way?
This should work (see the little difference):
money = float(1234.5) #next you used format without printing, nor affecting value of "money"
amountAsFormattedString = '${:,.2f}'.format(money)
print( amountAsFormattedString )
'cl' is not recognized as an internal or external command,
For me, this was related to the scenario described by Smi, with the difference being that vcvarsall.bat
itself was failing due to an invalid path.
This was cause by line-breaks within the path, which meant vcvarsall.bat
couldn't find the common tools directory for some reason.
Making a request to a RESTful API using python
Using requests:
import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '''{
"query": {
"bool": {
"must": [
{
"text": {
"record.document": "SOME_JOURNAL"
}
},
{
"text": {
"record.articleTitle": "farmers"
}
}
],
"must_not": [],
"should": []
}
},
"from": 0,
"size": 50,
"sort": [],
"facets": {}
}'''
response = requests.post(url, data=data)
Depending on what kind of response your API returns, you will then probably want to look at response.text
or response.json()
(or possibly inspect response.status_code
first). See the quickstart docs here, especially this section.
Getting the last n elements of a vector. Is there a better way than using the length() function?
I just add here something related. I was wanted to access a vector with backend indices, ie writting something like tail(x, i)
but to return x[length(x) - i + 1]
and not the whole tail.
Following commentaries I benchmarked two solutions:
accessRevTail <- function(x, n) {
tail(x,n)[1]
}
accessRevLen <- function(x, n) {
x[length(x) - n + 1]
}
microbenchmark::microbenchmark(accessRevLen(1:100, 87), accessRevTail(1:100, 87))
Unit: microseconds
expr min lq mean median uq max neval
accessRevLen(1:100, 87) 1.860 2.3775 2.84976 2.803 3.2740 6.755 100
accessRevTail(1:100, 87) 22.214 23.5295 28.54027 25.112 28.4705 110.833 100
So it appears in this case that even for small vectors, tail
is very slow comparing to direct access
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
Transpose a range in VBA
This gets you X and X' as variant arrays you can pass to another function.
Dim X() As Variant
Dim XT() As Variant
X = ActiveSheet.Range("InRng").Value2
XT = Application.Transpose(X)
To have the transposed values as a range, you have to pass it via a worksheet as in this answer. Without seeing how your covariance function works it's hard to see what you need.
Update a dataframe in pandas while iterating row by row
Increment the MAX number from a column. For Example :
df1 = [sort_ID, Column1,Column2]
print(df1)
My output :
Sort_ID Column1 Column2
12 a e
45 b f
65 c g
78 d h
MAX = df1['Sort_ID'].max() #This returns my Max Number
Now , I need to create a column in df2 and fill the column values which increments the MAX .
Sort_ID Column1 Column2
79 a1 e1
80 b1 f1
81 c1 g1
82 d1 h1
Note : df2 will initially contain only the Column1 and Column2 . we need the Sortid column to be created and incremental of the MAX from df1 .
How to set java_home on Windows 7?
This is the official solution for setting the Java environment from www.java.com - here.
There are solutions for Windows 7, Windows Vista, Windows XP, Linux/Solaris and other shells.
Example
Windows 7
- Select Computer from the Start menu
- Choose System Properties from the context menu
- Click Advanced system settings -> Advanced tab
- Click on Environment Variables, under System Variables, find PATH, and click on it.
- In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
- Reopen Command prompt window, and run your Java code.
How to prevent scanf causing a buffer overflow in C?
Directly using scanf(3)
and its variants poses a number of problems. Typically, users and non-interactive use cases are defined in terms of lines of input. It's rare to see a case where, if enough objects are not found, more lines will solve the problem, yet that's the default mode for scanf. (If a user didn't know to enter a number on the first line, a second and third line will probably not help.)
At least if you fgets(3)
you know how many input lines your program will need, and you won't have any buffer overflows...
How do I get the logfile from an Android device?
A simple way is to make your own log collector methods or even just an existing log collector app from the market.
For my apps I made a report functionality which sends the logs to my email (or even to another place - once you get the log you can do whether you want with it).
Here is a simple example about how to get the log file from a device:
Missing .map resource?
I had similar expirience like yours. I have Denwer server. When I loaded my http://new.new local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 jquery.min.map in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!
WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express
None of the other answers worked for me.
This did: (in Startup.cs)
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
// Here:
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
(or you can put it in WebApiConfig.cs):
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Here:
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
WSDL/SOAP Test With soapui
You can try opening the wsdl in web browser and saving with .wsdl extension. And set the WSDL in SOAP UI project to this .wsdl file.
This really works.
fill an array in C#
Say you want to fill with number 13.
int[] myarr = Enumerable.Range(0, 10).Select(n => 13).ToArray();
or
List<int> myarr = Enumerable.Range(0,10).Select(n => 13).ToList();
if you prefer a list.
Using Auto Layout in UITableView for dynamic cell layouts & variable row heights
An important enough gotcha I just ran into to post as an answer.
@smileyborg's answer is mostly correct. However, if you have any code in the layoutSubviews
method of your custom cell class, for instance setting the preferredMaxLayoutWidth
, then it won't be run with this code:
[cell.contentView setNeedsLayout];
[cell.contentView layoutIfNeeded];
It confounded me for awhile. Then I realized it's because those are only triggering layoutSubviews on the contentView
, not the cell itself.
My working code looks like this:
TCAnswerDetailAppSummaryCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"TCAnswerDetailAppSummaryCell"];
[cell configureWithThirdPartyObject:self.app];
[cell layoutIfNeeded];
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return height;
Note that if you are creating a new cell, I'm pretty sure you don't need to call setNeedsLayout
as it should already be set. In cases where you save a reference to a cell, you should probably call it. Either way it shouldn't hurt anything.
Another tip if you are using cell subclasses where you are setting things like preferredMaxLayoutWidth
. As @smileyborg mentions, "your table view cell hasn't yet had its width fixed to the table view's width". This is true, and trouble if you are doing your work in your subclass and not in the view controller. However you can simply set the cell frame at this point using the table width:
For instance in the calculation for height:
self.summaryCell = [self.tableView dequeueReusableCellWithIdentifier:@"TCAnswerDetailDefaultSummaryCell"];
CGRect oldFrame = self.summaryCell.frame;
self.summaryCell.frame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y, self.tableView.frame.size.width, oldFrame.size.height);
(I happen to cache this particular cell for re-use, but that's irrelevant).
How to obtain Telegram chat_id for a specific user?
I created a bot to get User or GroupChat id,
just send the /my_id
to telegram bot @get_id_bot
.
It does not only work for user chat ID, but also for group chat ID.
To get group chat ID, first you have to add the bot to the group,
then send /my_id
in the group.
Here's the link to the bot.
How do I get bit-by-bit data from an integer value in C?
If you don't want any loops, you'll have to write it out:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num = 7;
#if 0
bool arr[4] = { (num&1) ?true: false, (num&2) ?true: false, (num&4) ?true: false, (num&8) ?true: false };
#else
#define BTB(v,i) ((v) & (1u << (i))) ? true : false
bool arr[4] = { BTB(num,0), BTB(num,1), BTB(num,2), BTB(num,3)};
#undef BTB
#endif
printf("%d %d %d %d\n", arr[3], arr[2], arr[1], arr[0]);
return 0;
}
As demonstrated here, this also works in an initializer.
How to bind inverse boolean properties in WPF?
.Net Core Solution
Handles null situation and does not throw an exception, but returns true
if no value is presented; otherwise takes the inputted Boolean and reverses it.
public class BooleanToReverseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> !(bool?) value ?? true;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> !(value as bool?);
}
Xaml
IsEnabled="{Binding IsSuccess Converter={StaticResource BooleanToReverseConverter}}"
App.Xaml I like to put all my converter statics in the app.xaml file so I don't have to redeclare them throughout the windows/pages/controls of the project.
<Application.Resources>
<converters:BooleanToReverseConverter x:Key="BooleanToReverseConverter"/>
<local:FauxVM x:Key="VM" />
</Application.Resources>
To be clear converters:
is the namespace to the actual class implementation (xmlns:converters="clr-namespace:ProvingGround.Converters"
).
How to convert NSNumber to NSString
In Swift 3.0
let number:NSNumber = 25
let strValue = String(describing: number as NSNumber)
print("As String => \(strValue)")
We can get the number value in String.
python's re: return True if string contains regex pattern
Here's a function that does what you want:
import re
def is_match(regex, text):
pattern = re.compile(regex, text)
return pattern.search(text) is not None
The regular expression search method returns an object on success and None if the pattern is not found in the string. With that in mind, we return True as long as the search gives us something back.
Examples:
>>> is_match('ba[rzd]', 'foobar')
True
>>> is_match('ba[zrd]', 'foobaz')
True
>>> is_match('ba[zrd]', 'foobad')
True
>>> is_match('ba[zrd]', 'foobam')
False
How to normalize a NumPy array to within a certain range?
audio /= np.max(np.abs(audio),axis=0)
image *= (255.0/image.max())
Using /=
and *=
allows you to eliminate an intermediate temporary array, thus saving some memory. Multiplication is less expensive than division, so
image *= 255.0/image.max() # Uses 1 division and image.size multiplications
is marginally faster than
image /= image.max()/255.0 # Uses 1+image.size divisions
Since we are using basic numpy methods here, I think this is about as efficient a solution in numpy as can be.
In-place operations do not change the dtype of the container array. Since the desired normalized values are floats, the audio
and image
arrays need to have floating-point point dtype before the in-place operations are performed.
If they are not already of floating-point dtype, you'll need to convert them using astype
. For example,
image = image.astype('float64')
How to set 777 permission on a particular folder?
777
is a permission in Unix based system with full read/write/execute permission to owner, group and everyone.. in general we give this permission to assets which are not much needed to be hidden from public on a web server, for example images..
You said I am using windows 7.
if that means that your web server is Windows based then you should login to that and right click the folder and set permissions to everyone
and if you are on a windows client and server is unix/linux based then use some ftp software and in the parent directory right click and change the permission for the folder.
If you want permission to be set on sub-directories
too then usually their is option to set permission recursively use that.
And, if you feel like doing it from command line the use putty and login to server and go to the parent directory includes
and write the following command
chmod 0777 module_installation/
for recursive
chmod -R 0777 module_installation/
Hope this will help you
How do I ignore files in a directory in Git?
Both examples in the question are actually very bad examples that can lead to data loss!
My advice: never append /*
to directories in .gitignore files, unless you have a good reason!
A good reason would be for example what Jefromi wrote: "if you intend to subsequently un-ignore something in the directory".
The reason why it otherwise shouldn't be done is that appending /*
to directories does on the one hand work in the manner that it properly ignores all contents of the directory, but on the other hand it has a dangerous side effect:
If you execute git stash -u
(to temporarily stash tracked and untracked files) or git clean -df
(to delete untracked but keep ignored files) in your repository, all directories that are ignored with an appended /*
will be irreversibly deleted!
Some background
I had to learn this the hard way. Somebody in my team was appending /*
to some directories in our .gitignore. Over the time I had occasions where certain directories would suddenly disappear. Directories with gigabytes of local data needed by our application. Nobody could explain it and I always hat to re-download all data. After a while I got a notion that it might have to do with git stash
. One day I wanted to clean my local repo (while keeping ignored files) and I was using git clean -df
and again my data was gone. This time I had enough and investigated the issue. I finally figured that the reason is the appended /*
.
I assume it can be explained somehow by the fact that directory/*
does ignore all contents of the directory but not the directory itself. Thus it's neither considered tracked nor ignored when things get deleted. Even though git status
and git status --ignored
give a slightly different picture on it.
How to reproduce
Here is how to reproduce the behaviour. I'm currently using Git 2.8.4.
A directory called localdata/
with a dummy file in it (important.dat
) will be created in a local git repository and the contents will be ignored by putting /localdata/*
into the .gitignore
file. When one of the two mentioned git commands is executed now, the directory will be (unexpectedly) lost.
mkdir test
cd test
git init
echo "/localdata/*" >.gitignore
git add .gitignore
git commit -m "Add .gitignore."
mkdir localdata
echo "Important data" >localdata/important.dat
touch untracked-file
If you do a git status --ignored
here, you'll get:
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
untracked-file
Ignored files:
(use "git add -f <file>..." to include in what will be committed)
localdata/
Now either do
git stash -u
git stash pop
or
git clean -df
In both cases the allegedly ignored directory localdata
will be gone!
Not sure if this can be considered a bug, but I guess it's at least a feature that nobody needs.
I'll report that to the git development list and see what they think about it.
Argparse optional positional arguments?
As an extension to @VinaySajip answer. There are additional nargs
worth mentioning.
parser.add_argument('dir', nargs=1, default=os.getcwd())
N (an integer). N arguments from the command line will be gathered together into a list
parser.add_argument('dir', nargs='*', default=os.getcwd())
'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*'
, but multiple optional arguments with nargs='*'
is possible.
parser.add_argument('dir', nargs='+', default=os.getcwd())
'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.
parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())
argparse.REMAINDER
. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities
If the nargs
keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.
Edit (copied from a comment by @Acumenus) nargs='?'
The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.
What is lazy loading in Hibernate?
Lazy loading is a design pattern
commonly used in computer programming
to defer initialization of an object
until the point at which it is needed.
It can contribute to efficiency in the
program's operation if properly and
appropriately used
Wikipedia
Link of Lazy Loading from hibernate.org
Convert Java String to sql.Timestamp
Have you tried using Timestamp.valueOf(String)
? It looks like it should do almost exactly what you want - you just need to change the separator between your date and time to a space, and the ones between hours and minutes, and minutes and hours, to colons:
import java.sql.*;
public class Test {
public static void main(String[] args) {
String text = "2011-10-02 18:48:05.123456";
Timestamp ts = Timestamp.valueOf(text);
System.out.println(ts.getNanos());
}
}
Assuming you've already validated the string length, this will convert to the right format:
static String convertSeparators(String input) {
char[] chars = input.toCharArray();
chars[10] = ' ';
chars[13] = ':';
chars[16] = ':';
return new String(chars);
}
Alternatively, parse down to milliseconds by taking a substring and using Joda Time or SimpleDateFormat
(I vastly prefer Joda Time, but your mileage may vary). Then take the remainder of the string as another string and parse it with Integer.parseInt
. You can then combine the values pretty easily:
Date date = parseDateFromFirstPart();
int micros = parseJustLastThreeDigits();
Timestamp ts = new Timestamp(date.getTime());
ts.setNanos(ts.getNanos() + micros * 1000);
What is "loose coupling?" Please provide examples
In computer science there is another meaning for "loose coupling" that no one else has posted about here, so... Here goes - hopefully you'll give me some votes up so this isn't lost at the bottom of the heap! SURELY the subject of my answer belongs in any comprehensive answer to the question... To wit:
The term "Loose Coupling" first entered computing as a term used as an adjective regarding CPU architecture in a multi-CPU configuration. Its counterpart term is "tight coupling". Loose Coupling is when CPUs do not share many resources in common and Tight Coupling is when they do.
The term "system" can be confusing here so please parse the situation carefully.
Usually, but not always, multiple CPUs in a hardware configuration in which they exist within one system (as in individual "PC" boxes) would be tightly coupled. With the exception of some super-high-performance systems that have subsystems that actually share main memory across "systems", all divisible systems are loosely coupled.
The terms Tightly Coupled and Loosely Coupled were introduced before multi-threaded and multi-core CPUs were invented, so these terms may need some companions to fully articulate the situation today. And, indeed, today one may very well have a system that encompases both types in one overall system. Regarding current software systems, there are two common architectures, one of each variety, that are common enough these should be familliar.
First, since it was what the question was about, some examples of Loosely Coupled systems:
- VaxClusters
- Linux Clusters
In contrast, some Tightly Coupled examples:
- Semetrical-Multi-Processing (SMP) Operating systems - e.g. Fedora 9
- Multi-threaded CPUs
- Multi-Core CPUs
In today's computing, examples of both operating in a single overall system is not uncommon. For example, take modern Pentium dual or quad core CPUs running Fedora 9 - these are tightly-coupled computing systems. Then, combine several of them in a loosely coupled Linux Cluster and you now have both loosely and tightly coupled computing going on! Oh, isn't modern hardware wonderful!
SSIS Excel Import Forcing Incorrect Column Type
I've seen this issue before, it's Excel that is the issue not SSIS. Excel samples the 1st few rows and then infers the data type even if you explicitly set it to text. What you need to do is put this into the Excel file connection string in the SSIS package. This instruction tells Excel that the columns contain mixed data types and hints it to do extra checking before deciding that the column is a numeric type when in fact it's not.
;Extended Properties="IMEX=1"
It should work with this (in most cases). The safer thing to do is export the Excel data to tab delimited text and use SSIS to import that.
The response content cannot be parsed because the Internet Explorer engine is not available, or
In your invoke web request just use the parameter -UseBasicParsing
e.g. in your script (line 2) you should use:
$rss = Invoke-WebRequest -Uri $url -UseBasicParsing
According to the documentation, this parameter is necessary on systems where IE isn't installed or configured:
Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.
How to check if mysql database exists
I am using simply the following query:
"USE 'DBname'"
Then check if the result is FALSE.
Otherwise, there might be an access denied error, but I cannot know that.
So, in case of privileges involved, one can use:
"SHOW DATABASES LIKE 'DBname'"
as already mentioned earlier.
Code for Greatest Common Divisor in Python
I had to do something like this for a homework assignment using while loops. Not the most efficient way, but if you don't want to use a function this works:
num1 = 20
num1_list = []
num2 = 40
num2_list = []
x = 1
y = 1
while x <= num1:
if num1 % x == 0:
num1_list.append(x)
x += 1
while y <= num2:
if num2 % y == 0:
num2_list.append(y)
y += 1
xy = list(set(num1_list).intersection(num2_list))
print(xy[-1])
Setting the filter to an OpenFileDialog to allow the typical image formats?
To filter images files, use this code sample.
//Create a new instance of openFileDialog
OpenFileDialog res = new OpenFileDialog();
//Filter
res.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.gif;*.tif;...";
//When the user select the file
if (res.ShowDialog() == DialogResult.OK)
{
//Get the file's path
var filePath = res.FileName;
//Do something
....
}
Get first letter of a string from column
.str.get
This is the simplest to specify string methods
# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df
A B
0 xyz 123
1 abc 456
2 foobar 789
df.dtypes
A object
B int64
dtype: object
For string (read:object
) type columns, use
df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)
.str
handles NaNs by returning NaN as the output.
For non-numeric columns, an .astype
conversion is required beforehand, as shown in @Ed Chum's answer.
# Note that this won't work well if the data has NaNs.
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
List Comprehension and Indexing
There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.
# For string columns
df['C'] = [x[0] for x in df['A']]
# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
If your data has NaNs, then you will need to handle this appropriately with an if
/else
in the list comprehension,
df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2
A B
0 xyz 123.0
1 NaN 456.0
2 foobar NaN
# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]
# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]
A B C D
0 xyz 123.0 x 1
1 NaN 456.0 NaN 4
2 foobar NaN f NaN
Let's do some timeit tests on some larger data.
df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True)
%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])
%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])
12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
List comprehensions are 4x faster.
How can I turn a string into a list in Python?
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
SQLiteDatabase.query method
tableColumns
null
for all columns as in SELECT * FROM ...
new String[] { "column1", "column2", ... }
for specific columns as in SELECT column1, column2 FROM ...
- you can also put complex expressions here:
new String[] { "(SELECT max(column1) FROM table1) AS max" }
would give you a column named max
holding the max value of column1
whereClause
- the part you put after
WHERE
without that keyword, e.g. "column1 > 5"
- should include
?
for things that are dynamic, e.g. "column1=?"
-> see whereArgs
whereArgs
- specify the content that fills each
?
in whereClause
in the order they appear
the others
- just like
whereClause
the statement after the keyword or null
if you don't use it.
Example
String[] tableColumns = new String[] {
"column1",
"(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
"value1",
"value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
null, null, orderBy);
// since we have a named column we can do
int idx = c.getColumnIndex("max");
is equivalent to the following raw query
String queryString =
"SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
"WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);
By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '
.
Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";
because if value contains a '
your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--"
might even drop your table since the statement would become two statements and a comment:
SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'
using the args version XYZ'; DROP TABLE table1;--
would be escaped to 'XYZ''; DROP TABLE table1;--'
and would only be treated as a value. Even if the '
is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int
and other primitives directly into whereClause
though)
how can I set visible back to true in jquery
The problem is that since you are using ASP.NET controls with a runat
attribute, the ID of the control is not actually "test1". It's "test1" with a long string attached to it.
socket programming multiple client to one server
This is the echo server handling multiple clients... Runs fine and good using Threads
// echo server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server_X_Client {
public static void main(String args[]){
Socket s=null;
ServerSocket ss2=null;
System.out.println("Server Listening......");
try{
ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined
}
catch(IOException e){
e.printStackTrace();
System.out.println("Server error");
}
while(true){
try{
s= ss2.accept();
System.out.println("connection Established");
ServerThread st=new ServerThread(s);
st.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
class ServerThread extends Thread{
String line=null;
BufferedReader is = null;
PrintWriter os=null;
Socket s=null;
public ServerThread(Socket s){
this.s=s;
}
public void run() {
try{
is= new BufferedReader(new InputStreamReader(s.getInputStream()));
os=new PrintWriter(s.getOutputStream());
}catch(IOException e){
System.out.println("IO error in server thread");
}
try {
line=is.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
System.out.println("Response to Client : "+line);
line=is.readLine();
}
} catch (IOException e) {
line=this.getName(); //reused String line for getting thread name
System.out.println("IO Error/ Client "+line+" terminated abruptly");
}
catch(NullPointerException e){
line=this.getName(); //reused String line for getting thread name
System.out.println("Client "+line+" Closed");
}
finally{
try{
System.out.println("Connection Closing..");
if (is!=null){
is.close();
System.out.println(" Socket Input Stream Closed");
}
if(os!=null){
os.close();
System.out.println("Socket Out Closed");
}
if (s!=null){
s.close();
System.out.println("Socket Closed");
}
}
catch(IOException ie){
System.out.println("Socket Close Error");
}
}//end finally
}
}
Also here is the code for the client.. Just execute this code for as many times as you want to create multiple client..
// A simple Client Server Protocol .. Client for Echo Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class NetworkClient {
public static void main(String args[]) throws IOException{
InetAddress address=InetAddress.getLocalHost();
Socket s1=null;
String line=null;
BufferedReader br=null;
BufferedReader is=null;
PrintWriter os=null;
try {
s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
br= new BufferedReader(new InputStreamReader(System.in));
is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
os= new PrintWriter(s1.getOutputStream());
}
catch (IOException e){
e.printStackTrace();
System.err.print("IO Exception");
}
System.out.println("Client Address : "+address);
System.out.println("Enter Data to echo Server ( Enter QUIT to end):");
String response=null;
try{
line=br.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
response=is.readLine();
System.out.println("Server Response : "+response);
line=br.readLine();
}
}
catch(IOException e){
e.printStackTrace();
System.out.println("Socket read Error");
}
finally{
is.close();os.close();br.close();s1.close();
System.out.println("Connection Closed");
}
}
}
Finding the handle to a WPF window
If you want window handles for ALL of your application's Window
s for some reason, you can use the Application.Windows
property to get at all the Windows and then use WindowInteropHandler
to get at their handles as you have already demonstrated.
python catch exception and continue try block
No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.
What about a for-loop though?
funcs = do_smth1, do_smth2
for func in funcs:
try:
func()
except Exception:
pass # or you could use 'continue'
Note however that it is considered a bad practice to have a bare except
. You should catch for a specific exception instead. I captured for Exception
because that's as good as I can do without knowing what exceptions the methods might throw.
How would I access variables from one class to another?
var1 and var2 is an Instance variables of ClassA. Create an Instance of ClassB and when calling the methodA it will check the methodA in Child class (ClassB) first, If methodA is not present in ClassB you need to invoke the ClassA by using the super() method which will get you all the methods implemented in ClassA. Now, you can access all the methods and attributes of ClassB.
class ClassA(object):
def __init__(self):
self.var1 = 1
self.var2 = 2
def methodA(self):
self.var1 = self.var1 + self.var2
return self.var1
class ClassB(ClassA):
def __init__(self):
super().__init__()
print("var1",self.var1)
print("var2",self.var2)
object1 = ClassB()
sum = object1.methodA()
print(sum)
The name 'ConfigurationManager' does not exist in the current context
In your project, right-click, Add Reference..., in the .NET tab, find the System.Configuration
component name and click OK.
using System.Configuration
tells the compiler/IntelliSense to search in that namespace for any classes you use. Otherwise, you would have to use the full name (System.Configuration.ConfigurationManager
) every time. But if you don't add the reference, that namespace/class will not be found anywhere.
Note that a DLL can have any namespace, so the file System.Configuration.dll
could, in theory, have the namespace Some.Random.Name
. For clarity/consistency they're usually the same, but there are exceptions.
python: sys is not defined
Move import sys
outside of the try
-except
block:
import sys
try:
# ...
except ImportError:
# ...
If any of the imports before the import sys
line fails, the rest of the block is not executed, and sys
is never imported. Instead, execution jumps to the exception handling block, where you then try to access a non-existing name.
sys
is a built-in module anyway, it is always present as it holds the data structures to track imports; if importing sys
fails, you have bigger problems on your hand (as that would indicate that all module importing is broken).
__FILE__, __LINE__, and __FUNCTION__ usage in C++
FYI: g++ offers the non-standard __PRETTY_FUNCTION__ macro. Until just now I did not know about C99 __func__ (thanks Evan!). I think I still prefer __PRETTY_FUNCTION__ when it's available for the extra class scoping.
PS:
static string getScopedClassMethod( string thePrettyFunction )
{
size_t index = thePrettyFunction . find( "(" );
if ( index == string::npos )
return thePrettyFunction; /* Degenerate case */
thePrettyFunction . erase( index );
index = thePrettyFunction . rfind( " " );
if ( index == string::npos )
return thePrettyFunction; /* Degenerate case */
thePrettyFunction . erase( 0, index + 1 );
return thePrettyFunction; /* The scoped class name. */
}
How to create windows service from java jar?
Use nssm.exe but remember to set the AppDirectory or any required libraries or resources will not be accessible. By default nssm set the current working directory to the that of the application, java.exe, not the jar.
So do this to create a batch script:
pushd <path-to-jar>
nssm.exe install "<service-name>" "<path-to-java.exe>" "-jar <name-of-jar>"
nssm.exe set "<service-name>" AppDirectory "<path-to-jar>"
This should fix the service paused issue.
How to add a single item to a Pandas Series
Here is another thought n for appending multiple items in one line without changing the name of series. However, this may be not as efficient as the other answer.
>>> df = pd.Series(np.random.random(5), name='random')
>>> df
0 0.363885
1 0.402623
2 0.450449
3 0.172917
4 0.983481
Name: random, dtype: float64
>>> df.to_frame().T.assign(a=3, b=2, c=5).squeeze()
0 0.363885
1 0.402623
2 0.450449
3 0.172917
4 0.983481
a 3.000000
b 2.000000
c 5.000000
Name: random, dtype: float64
SQL Server ORDER BY date and nulls last
smalldatetime
has range up to June 6, 2079 so you can use
ORDER BY ISNULL(Next_Contact_Date, '2079-06-05T23:59:00')
If no legitimate records will have that date.
If this is not an assumption you fancy relying on a more robust option is sorting on two columns.
ORDER BY CASE WHEN Next_Contact_Date IS NULL THEN 1 ELSE 0 END, Next_Contact_Date
Both of the above suggestions are not able to use an index to avoid a sort however and give similar looking plans.
One other possibility if such an index exists is
SELECT 1 AS Grp, Next_Contact_Date
FROM T
WHERE Next_Contact_Date IS NOT NULL
UNION ALL
SELECT 2 AS Grp, Next_Contact_Date
FROM T
WHERE Next_Contact_Date IS NULL
ORDER BY Grp, Next_Contact_Date
PHP list of specific files in a directory
$it = new RegexIterator(new DirectoryIterator("."), "/\\.xml\$/i"));
foreach ($it as $filename) {
//...
}
You can also use the recursive variants of the iterators to traverse an entire directory hierarchy.
How to replace all special character into a string using C#
Assume you want to replace symbols which are not digits or letters (and _ character as @Guffa correctly pointed):
string input = "Hello@Hello&Hello(Hello)";
string result = Regex.Replace(input, @"[^\w\d]", ",");
// Hello,Hello,Hello,Hello,
You can add another symbols which should not be replaced. E.g. if you want white space symbols to stay, then just add \s
to pattern: \[^\w\d\s]
How to set password for Redis?
sudo nano /etc/redis/redis.conf
find and uncomment line # requirepass foobared
, then restart server
now you password is foobared
How do I specify row heights in CSS Grid layout?
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
How to list the properties of a JavaScript object?
The solution work on my cases and cross-browser:
var getKeys = function(obj) {
var type = typeof obj;
var isObjectType = type === 'function' || type === 'object' || !!obj;
// 1
if(isObjectType) {
return Object.keys(obj);
}
// 2
var keys = [];
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
keys.push(i)
}
}
if(keys.length) {
return keys;
}
// 3 - bug for ie9 <
var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');
if(hasEnumbug) {
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
var nonEnumIdx = nonEnumerableProps.length;
while (nonEnumIdx--) {
var prop = nonEnumerableProps[nonEnumIdx];
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
keys.push(prop);
}
}
}
return keys;
};
How to use ArrayAdapter<myClass>
Implement custom adapter for your class:
public class MyClassAdapter extends ArrayAdapter<MyClass> {
private static class ViewHolder {
private TextView itemView;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.listview_association, parent, false);
viewHolder = new ViewHolder();
viewHolder.itemView = (TextView) convertView.findViewById(R.id.ItemView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
MyClass item = getItem(position);
if (item!= null) {
// My layout has only one TextView
// do whatever you want with your string and long
viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));
}
return convertView;
}
}
For those not very familiar with the Android framework, this is explained in better detail here: https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView.
SCRIPT438: Object doesn't support property or method IE
I had the following
document.getElementById("search-button") != null
which worked fine in all browsers except ie8. ( I didnt check ie6 or ie7)
I changed it to
document.getElementById("searchBtn") != null
and updated the id attribute on the field in my html and it now works in ie8
Angular - ui-router get previous state
Ok, I know that I am late to the party here, but I am new to angular. I am trying to make this fit into the John Papa style guide here. I wanted to make this reusable so I created in a block. Here is what I came up with:
previousStateProvider
(function () {
'use strict';
angular.module('blocks.previousState')
.provider('previousState', previousStateProvider);
previousStateProvider.$inject = ['$rootScopeProvider'];
function previousStateProvider($rootScopeProvider) {
this.$get = PreviousState;
PreviousState.$inject = ['$rootScope'];
/* @ngInject */
function PreviousState($rootScope) {
$rootScope.previousParms;
$rootScope.previousState;
$rootScope.currentState;
$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
$rootScope.previousParms = fromParams;
$rootScope.previousState = from.name;
$rootScope.currentState = to.name;
});
}
}
})();
core.module
(function () {
'use strict';
angular.module('myApp.Core', [
// Angular modules
'ngMessages',
'ngResource',
// Custom modules
'blocks.previousState',
'blocks.router'
// 3rd Party Modules
]);
})();
core.config
(function () {
'use strict';
var core = angular.module('myApp.Core');
core.run(appRun);
function appRun(previousState) {
// do nothing. just instantiating the state handler
}
})();
Any critique on this code will only help me, so please let me know where I can improve this code.
Add params to given URL in Python
Use the various urlparse
functions to tear apart the existing URL, urllib.urlencode()
on the combined dictionary, then urlparse.urlunparse()
to put it all back together again.
Or just take the result of urllib.urlencode()
and concatenate it to the URL appropriately.
Playing HTML5 video on fullscreen in android webview
Thank you so much for that class, Cristian.
I made a minor tweak to it so that the custom loading view is optional, like so:
@Override
public View getVideoLoadingProgressView() // Video will start loading, only called in the case of VideoView (typically API level 10-)
{
if (loadingView == null)
{
return super.getVideoLoadingProgressView();
}
else
{
loadingView.setVisibility(View.VISIBLE);
return loadingView;
}
}
I also added a new constructor that just takes two parameters. Anyway, just a minor simplification if you don't need the loading view. Thanks again for providing this.
Calculate RSA key fingerprint
If your SSH agent is running, it is
ssh-add -l
to list RSA fingerprints of all identities, or -L
for listing public keys.
If your agent is not running, try:
ssh-agent sh -c 'ssh-add; ssh-add -l'
And for your public keys:
ssh-agent sh -c 'ssh-add; ssh-add -L'
If you get the message: 'The agent has no identities.', then you have to generate your RSA key by ssh-keygen
first.
Check if a class is derived from a generic class
(Reposted due to a massive rewrite)
JaredPar's code answer is fantastic, but I have a tip that would make it unnecessary if your generic types are not based on value type parameters. I was hung up on why the "is" operator would not work, so I have also documented the results of my experimentation for future reference. Please enhance this answer to further enhance its clarity.
TIP:
If you make certain that your GenericClass implementation inherits from an abstract non-generic base class such as GenericClassBase, you could ask the same question without any trouble at all like this:
typeof(Test).IsSubclassOf(typeof(GenericClassBase))
IsSubclassOf()
My testing indicates that IsSubclassOf() does not work on parameterless generic types such as
typeof(GenericClass<>)
whereas it will work with
typeof(GenericClass<SomeType>)
Therefore the following code will work for any derivation of GenericClass<>, assuming you are willing to test based on SomeType:
typeof(Test).IsSubclassOf(typeof(GenericClass<SomeType>))
The only time I can imagine that you would want to test by GenericClass<> is in a plug-in framework scenario.
Thoughts on the "is" operator
At design-time C# does not allow the use of parameterless generics because they are essentially not a complete CLR type at that point. Therefore, you must declare generic variables with parameters, and that is why the "is" operator is so powerful for working with objects. Incidentally, the "is" operator also can not evaluate parameterless generic types.
The "is" operator will test the entire inheritance chain, including interfaces.
So, given an instance of any object, the following method will do the trick:
bool IsTypeof<T>(object t)
{
return (t is T);
}
This is sort of redundant, but I figured I would go ahead and visualize it for everybody.
Given
var t = new Test();
The following lines of code would return true:
bool test1 = IsTypeof<GenericInterface<SomeType>>(t);
bool test2 = IsTypeof<GenericClass<SomeType>>(t);
bool test3 = IsTypeof<Test>(t);
On the other hand, if you want something specific to GenericClass, you could make it more specific, I suppose, like this:
bool IsTypeofGenericClass<SomeType>(object t)
{
return (t is GenericClass<SomeType>);
}
Then you would test like this:
bool test1 = IsTypeofGenericClass<SomeType>(t);
Search code inside a Github project
Go here: https://github.com/search and enter "pattern repo:user_name/repo_name".
For example, to search for cnn_learner
in the fastai
repo of user fastai
, enter this:
cnn_learner repo:fastai/fastai
That's it. The only annoyance is you'll need an extra click. It will tell you:
We couldn’t find any repositories matching 'cnn_learner
repo:fastai/fastai'
because by default it searches for repositories matching that search string...
So just click on the left on "Code" and it will display what you want.
Or get the code search results directly with a URL like this:
https://github.com/search?q=cnn_learner+repo%3Afastai%2Ffastai&type=code
JavaScript object: access variable property by name as string
You don't need a function for it - simply use the bracket notation:
var side = columns['right'];
This is equal to dot notation, var side = columns.right;
, except the fact that right
could also come from a variable, function return value, etc., when using bracket notation.
If you NEED a function for it, here it is:
function read_prop(obj, prop) {
return obj[prop];
}
To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:
var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};
you can access property x
of c
as follows:
var cx = foo['c']['x']
If a property is undefined, an attempt to reference it will return undefined
(not null
or false
):
foo['c']['q'] === null
// returns false
foo['c']['q'] === false
// returns false
foo['c']['q'] === undefined
// returns true
Creating a Jenkins environment variable using Groovy
On my side it only worked this way by replacing an existing parameter.
def artifactNameParam = new StringParameterValue('CopyProjectArtifactName', 'bla bla bla')
build.replaceAction(new ParametersAction(artifactNameParam))
Additionally this script must be run with system groovy.
A groovy must be manually installed on that system and the bin dir of groovy must be added to path. Additionally in the lib folder I had to add jenkins-core.jar.
Then it was possible to modify a parameter in a groovy script and get the modified value in a batch script after to continue work.
The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
How to count items in JSON data
import json
json_data = json.dumps({
"result":[
{
"run":[
{
"action":"stop"
},
{
"action":"start"
},
{
"action":"start"
}
],
"find": "true"
}
]
})
item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])
Convert it in dict.
When should we use mutex and when should we use semaphore
See "The Toilet Example" - http://pheatt.emporia.edu/courses/2010/cs557f10/hand07/Mutex%20vs_%20Semaphore.htm:
Mutex:
Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue.
Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section."
Ref: Symbian Developer Library
(A mutex is really a semaphore with value 1.)
Semaphore:
Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.
Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)."
Ref: Symbian Developer Library
How to define and use function inside Jenkins Pipeline config?
First off, you shouldn't add $
when you're outside of strings ($class
in your first function being an exception), so it should be:
def doCopyMibArtefactsHere(projectName) {
step ([
$class: 'CopyArtifact',
projectName: projectName,
filter: '**/**.mib',
fingerprintArtifacts: true,
flatten: true
]);
}
def BuildAndCopyMibsHere(projectName, params) {
build job: project, parameters: params
doCopyMibArtefactsHere(projectName)
}
...
Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:
...
node {
stage('Prepare Mib'){
BuildAndCopyMibsHere('project1', null)
}
}
... or you need to add a default value to the functions' second argument:
def BuildAndCopyMibsHere(projectName, params = null) {
build job: project, parameters: params
doCopyMibArtefactsHere($projectName)
}
Does Python have a string 'contains' substring method?
if needle in haystack:
is the normal use, as @Michael says -- it relies on the in
operator, more readable and faster than a method call.
If you truly need a method instead of an operator (e.g. to do some weird key=
for a very peculiar sort...?), that would be 'haystack'.__contains__
. But since your example is for use in an if
, I guess you don't really mean what you say;-). It's not good form (nor readable, nor efficient) to use special methods directly -- they're meant to be used, instead, through the operators and builtins that delegate to them.
Action Bar's onClick listener for the Home button
if we use the system given action bar following code works fine
getActionBar().setHomeButtonEnabled(true);
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home:
//do your action here.
break;
}
return true;
}
How to implement a ConfigurationSection with a ConfigurationElementCollection
If you are looking for a custom configuration section like following
<CustomApplicationConfig>
<Credentials Username="itsme" Password="mypassword"/>
<PrimaryAgent Address="10.5.64.26" Port="3560"/>
<SecondaryAgent Address="10.5.64.7" Port="3570"/>
<Site Id="123" />
<Lanes>
<Lane Id="1" PointId="north" Direction="Entry"/>
<Lane Id="2" PointId="south" Direction="Exit"/>
</Lanes>
</CustomApplicationConfig>
then you can use my implementation of configuration section so to get started add System.Configuration
assembly reference to your project
Look at the each nested elements I used, First one is Credentials with two attributes so lets add it first
Credentials Element
public class CredentialsConfigElement : System.Configuration.ConfigurationElement
{
[ConfigurationProperty("Username")]
public string Username
{
get
{
return base["Username"] as string;
}
}
[ConfigurationProperty("Password")]
public string Password
{
get
{
return base["Password"] as string;
}
}
}
PrimaryAgent and SecondaryAgent
Both has the same attributes and seem like a Address to a set of servers for a primary and a failover, so you just need to create one element class for both of those like following
public class ServerInfoConfigElement : ConfigurationElement
{
[ConfigurationProperty("Address")]
public string Address
{
get
{
return base["Address"] as string;
}
}
[ConfigurationProperty("Port")]
public int? Port
{
get
{
return base["Port"] as int?;
}
}
}
I'll explain how to use two different element with one class later in this post, let us skip the SiteId as there is no difference in it. You just have to create one class same as above with one property only. let us see how to implement Lanes collection
it is splitted in two parts first you have to create an element implementation class then you have to create collection element class
LaneConfigElement
public class LaneConfigElement : ConfigurationElement
{
[ConfigurationProperty("Id")]
public string Id
{
get
{
return base["Id"] as string;
}
}
[ConfigurationProperty("PointId")]
public string PointId
{
get
{
return base["PointId"] as string;
}
}
[ConfigurationProperty("Direction")]
public Direction? Direction
{
get
{
return base["Direction"] as Direction?;
}
}
}
public enum Direction
{
Entry,
Exit
}
you can notice that one attribute of LanElement
is an Enumeration and if you try to use any other value in configuration which is not defined in Enumeration application will throw an System.Configuration.ConfigurationErrorsException
on startup. Ok lets move on to Collection Definition
[ConfigurationCollection(typeof(LaneConfigElement), AddItemName = "Lane", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class LaneConfigCollection : ConfigurationElementCollection
{
public LaneConfigElement this[int index]
{
get { return (LaneConfigElement)BaseGet(index); }
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
public void Add(LaneConfigElement serviceConfig)
{
BaseAdd(serviceConfig);
}
public void Clear()
{
BaseClear();
}
protected override ConfigurationElement CreateNewElement()
{
return new LaneConfigElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((LaneConfigElement)element).Id;
}
public void Remove(LaneConfigElement serviceConfig)
{
BaseRemove(serviceConfig.Id);
}
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
public void Remove(String name)
{
BaseRemove(name);
}
}
you can notice that I have set the AddItemName = "Lane"
you can choose whatever you like for your collection entry item, i prefer to use "add" the default one but i changed it just for the sake of this post.
Now all of our nested Elements have been implemented now we should aggregate all of those in a class which has to implement System.Configuration.ConfigurationSection
CustomApplicationConfigSection
public class CustomApplicationConfigSection : System.Configuration.ConfigurationSection
{
private static readonly ILog log = LogManager.GetLogger(typeof(CustomApplicationConfigSection));
public const string SECTION_NAME = "CustomApplicationConfig";
[ConfigurationProperty("Credentials")]
public CredentialsConfigElement Credentials
{
get
{
return base["Credentials"] as CredentialsConfigElement;
}
}
[ConfigurationProperty("PrimaryAgent")]
public ServerInfoConfigElement PrimaryAgent
{
get
{
return base["PrimaryAgent"] as ServerInfoConfigElement;
}
}
[ConfigurationProperty("SecondaryAgent")]
public ServerInfoConfigElement SecondaryAgent
{
get
{
return base["SecondaryAgent"] as ServerInfoConfigElement;
}
}
[ConfigurationProperty("Site")]
public SiteConfigElement Site
{
get
{
return base["Site"] as SiteConfigElement;
}
}
[ConfigurationProperty("Lanes")]
public LaneConfigCollection Lanes
{
get { return base["Lanes"] as LaneConfigCollection; }
}
}
Now you can see that we have two properties with name PrimaryAgent
and SecondaryAgent
both have the same type now you can easily understand why we had only one implementation class against these two element.
Before you can use this newly invented configuration section in your app.config (or web.config) you just need to tell you application that you have invented your own configuration section and give it some respect, to do so you have to add following lines in app.config (may be right after start of root tag).
<configSections>
<section name="CustomApplicationConfig" type="MyNameSpace.CustomApplicationConfigSection, MyAssemblyName" />
</configSections>
NOTE: MyAssemblyName should be without .dll e.g. if you assembly file name is myDll.dll then use myDll instead of myDll.dll
to retrieve this configuration use following line of code any where in your application
CustomApplicationConfigSection config = System.Configuration.ConfigurationManager.GetSection(CustomApplicationConfigSection.SECTION_NAME) as CustomApplicationConfigSection;
I hope above post would help you to get started with a bit complicated kind of custom config sections.
Happy Coding :)
****Edit****
To Enable LINQ on LaneConfigCollection
you have to implement IEnumerable<LaneConfigElement>
And Add following implementation of GetEnumerator
public new IEnumerator<LaneConfigElement> GetEnumerator()
{
int count = base.Count;
for (int i = 0; i < count; i++)
{
yield return base.BaseGet(i) as LaneConfigElement;
}
}
for the people who are still confused about how yield really works read this nice article
Two key points taken from above article are
it doesn’t really end the method’s execution. yield return pauses the
method execution and the next time you call it (for the next
enumeration value), the method will continue to execute from the last
yield return call. It sounds a bit confusing I think… (Shay Friedman)
Yield is not a feature of the .Net runtime. It is just a C# language
feature which gets compiled into simple IL code by the C# compiler. (Lars Corneliussen)
How to connect to mysql with laravel?
You probably only forgot to create database. Enter your PHPMyAdmin and do it from there.
Edit: Definitely don't go with Maulik's answer. Not only it is using mysql_ extenstion (which is commonly recognized bad practice), Laravel is also taking care of your connections using PDO.
How to run a Python script in the background even after I logout SSH?
Here is a simple solution inside python using a decorator:
import os, time
def daemon(func):
def wrapper(*args, **kwargs):
if os.fork(): return
func(*args, **kwargs)
os._exit(os.EX_OK)
return wrapper
@daemon
def my_func(count=10):
for i in range(0,count):
print('parent pid: %d' % os.getppid())
time.sleep(1)
my_func(count=10)
#still in parent thread
time.sleep(2)
#after 2 seconds the function my_func lives on is own
You can of course replace the content of your bgservice.py
file in place of my_func
.
Capturing TAB key in text box
I would advise against changing the default behaviour of a key. I do as much as possible without touching a mouse, so if you make my tab key not move to the next field on a form I will be very aggravated.
A shortcut key could be useful however, especially with large code blocks and nesting. Shift-TAB is a bad option because that normally takes me to the previous field on a form. Maybe a new button on the WMD editor to insert a code-TAB, with a shortcut key, would be possible?
How to select last two characters of a string
Slice can be used to find the substring. When we know the indexes we can use an alternative solution like index wise adder. Both are taking roughly the same time for execution.
_x000D_
_x000D_
const primitiveStringMember = "my name is Mate";
const objectStringMember = new String("my name is Mate");
console.log(typeof primitiveStringMember);//string
console.log(typeof objectStringMember);//object
/* However when we use . operator to string primitive type, JS will wrap up the string with object. That's why we can use the methods String object type for the primitive type string.
*/
//Slice method
const t0 = performance.now();
slicedString = primitiveStringMember.slice(-2);//te
const t1 = performance.now();
console.log(`Call to do slice took ${t1 - t0} milliseconds.`);
//index vise adder method
const t2 = performance.now();
length = primitiveStringMember.length
neededString = primitiveStringMember[length-2]+primitiveStringMember[length-1];//te
const t3 = performance.now();
console.log(`Call to do index adder took ${t3 - t2} milliseconds.`);
_x000D_
_x000D_
_x000D_
Mac OS X - EnvironmentError: mysql_config not found
If you don't want to install full mysql, we can fix this by just installing mysqlclient
brew install mysqlclient
Once cmd is completed it will ask to add below line to ~/.bash_profile
:
echo 'export PATH="/usr/local/opt/mysql-client/bin:$PATH"' >> ~/.bash_profile
Close terminal and start new terminal and proceed with pip install mysqlclient
Closing Application with Exit button
You cannot exit your application. Using android.finish()
won't exit
the application, it just kills the activity. It's used when we don't
want to see the previous activity on back button click. The
application automatically exits when you switch off the device. The
Android architecture does not support exiting the app. If you want,
you can forcefully exit the app, but that's not considered good
practice.
How do I find the parent directory in C#?
Since nothing else I have found helps to solve this in a truly normalized way, here is another answer.
Note that some answers to similar questions try to use the Uri
type, but that struggles with trailing slashes vs. no trailing slashes too.
My other answer on this page works for operations that put the file system to work, but if we want to have the resolved path right now (such as for comparison reasons), without going through the file system, C:/Temp/..
and C:/
would be considered different. Without going through the file system, navigating in that manner does not provide us with a normalized, properly comparable path.
What can we do?
We will build on the following discovery:
Path.GetDirectoryName(path + "/") ?? ""
will reliably give us a directory path without a trailing slash.
- Adding a slash (as
string
, not as char
) will treat a null
path the same as it treats ""
.
GetDirectoryName
will refrain from discarding the last path component thanks to the added slash.
GetDirectoryName
will normalize slashes and navigational dots.
- This includes the removal of any trailing slashes.
- This includes collapsing
..
by navigating up.
GetDirectoryName
will return null
for an empty path, which we coalesce to ""
.
How do we use this?
First, normalize the input path:
dirPath = Path.GetDirectoryName(dirPath + "/") ?? "";
Then, we can get the parent directory, and we can repeat this operation any number of times to navigate further up:
// This is reliable if path results from this or the previous operation
path = Path.GetDirectoryName(path);
Note that we have never touched the file system. No part of the path needs to exist, as it would if we had used DirectoryInfo
.
Java SSL: how to disable hostname verification
There is no hostname verification in standard Java SSL sockets or indeed SSL, so that's why you can't set it at that level. Hostname verification is part of HTTPS (RFC 2818): that's why it manifests itself as javax.net.ssl.HostnameVerifier, which is applied to an HttpsURLConnection.
Creating and returning Observable from Angular 2 Service
In the service.ts file -
a. import 'of' from observable/of
b. create a json list
c. return json object using Observable.of()
Ex. -
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
@Injectable()
export class ClientListService {
private clientList;
constructor() {
this.clientList = [
{name: 'abc', address: 'Railpar'},
{name: 'def', address: 'Railpar 2'},
{name: 'ghi', address: 'Panagarh'},
{name: 'jkl', address: 'Panagarh 2'},
];
}
getClientList () {
return Observable.of(this.clientList);
}
};
In the component where we are calling the get function of the service -
this.clientListService.getClientList().subscribe(res => this.clientList = res);
Test if number is odd or even
You were right in thinking mod was a good place to start. Here is an expression which will return true if $number
is even, false if odd:
$number % 2 == 0
Works for every integerPHP value, see as well Arithmetic OperatorsPHP.
Example:
$number = 20;
if ($number % 2 == 0) {
print "It's even";
}
Output:
It's even
how to replace characters in hive?
Custom SerDe might be a way to do it. Or you could use some kind of mediation process with regex_replace:
create table tableB as
select
columnA
regexp_replace(description, '\\t', '') as description
from tableA
;
What is so bad about singletons?
Monopoly is the devil and singletons with non-readonly/mutable state are the 'real' problem...
After reading Singletons are Pathological Liars as suggested in jason's answer I came across this little tidbit that provides the best presented example of how singletons are often misused.
Global is bad because:
- a. It causes namespace conflict
- b. It exposes the state in a unwarranted fashion
When it comes to Singletons
- a. The explicit OO way of calling them, prevents the conflicts, so point a. is not an issue
- b. Singletons without state are (like factories) are not a problem. Singletons with state can again fall in two categories, those which are immutable or write once and read many (config/property files). These are not bad. Mutable Singletons, which are kind of reference holders are the ones which you are speaking of.
In the last statement he's referring to the blog's concept of 'singletons are liars'.
How does this apply to Monopoly?
To start a game of monopoly, first:
- we establish the rules first so everybody is on the same page
- everybody is given an equal start at the beginning of the game
- only one set of rules is presented to avoid confusion
- the rules aren't allowed to change throughout the game
Now, for anybody who hasn't really played monopoly, these standards are ideal at best. A defeat in monopoly is hard to swallow because, monopoly is about money, if you lose you have to painstakingly watch the rest of the players finish the game, and losses are usually swift and crushing. So, the rules usually get twisted at some point to serve the self-interest of some of the players at the expense of the others.
So you're playing monopoly with friends Bob, Joe, and Ed. You're swiftly building your empire and consuming market share at an exponential rate. Your opponents are weakening and you start to smell blood (figuratively). Your buddy Bob put all of his money into gridlocking as many low-value properties as possible but his isn't receiving a high return on investment the way he expected. Bob, as a stroke of bad luck, lands on your Boardwalk and is excised from the game.
Now the game goes from friendly dice-rolling to serious business. Bob has been made the example of failure and Joe and Ed don't want to end up like 'that guy'. So, being the leading player you, all of a sudden, become the enemy. Joe and Ed start practicing under-the-table trades, behind-the-back money injections, undervalued house-swapping and generally anything to weaken you as a player until one of them rises to the top.
Then, instead of one of them winning, the process starts all over. All of a sudden, a finite set of rules becomes a moving target and the game degenerates into the type of social interactions that would make up the foundation of every high-rated reality TV show since Survivor. Why, because the rules are changing and there's no consensus on how/why/what they're supposed to represent, and more importantly, there's no one person making the decisions. Every player in the game, at that point, is making his/her own rules and chaos ensues until two of the players are too tired to keep up the charade and slowly give up.
So, if a rulebook for a game accurately represented a singleton, the monopoly rulebook would be an example of abuse.
How does this apply to programming?
Aside from all of the obvious thread-safety and synchronization issues that mutable singletons present... If you have one set of data, that is capable of being read/manipulated by multiple different sources concurrently and exists during the lifetime of the application execution, it's probably a good time to step back and ask "am I using the right type of data structure here".
Personally, I have seen a programmer abuse a singleton by using it as some sort of twisted cross-thread database store within an application. Having worked on the code directly, I can attest that it was a slow (because of all the thread locks needed to make it thread-safe) and a nightmare to work on (because of the unpredictable/intermittent nature of synchronization bugs), and nearly impossible to test under 'production' conditions. Sure, a system could have been developed using polling/signaling to overcome some of the performance issues but that wouldn't solve the issues with testing and, why bother when a 'real' database can already accomplish the same functionality in a much more robust/scalable manner.
A Singleton is only an option if you need what a singleton provides. A write-one read-only instance of an object. That same rule should cascade to the object's properties/members as well.
How to import component into another root component in Angular 2
For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations
key, so add CoursesComponent
in your main module declarations
as below and remove directives
from AppComponent
metadata.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, CoursesComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*
SignalR provides ConnectionId for each connection. To find which connection belongs to whom (the user), we need to create a mapping between the connection and the user. This depends on how you identify a user in your application.
In SignalR 2.0, this is done by using the inbuilt IPrincipal.Identity.Name
, which is the logged in user identifier as set during the ASP.NET authentication.
However, you may need to map the connection with the user using a different identifier instead of using the Identity.Name. For this purpose this new provider can be used with your custom implementation for mapping user with the connection.
Example of Mapping SignalR Users to Connections using IUserIdProvider
Lets assume our application uses a userId
to identify each user. Now, we need to send message to a specific user. We have userId
and message
, but SignalR must also know the mapping between our userId and the connection.
To achieve this, first we need to create a new class which implements IUserIdProvider
:
public class CustomUserIdProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
// your logic to fetch a user identifier goes here.
// for example:
var userId = MyCustomUserClass.FindUserId(request.User.Identity.Name);
return userId.ToString();
}
}
The second step is to tell SignalR to use our CustomUserIdProvider
instead of the default implementation. This can be done in the Startup.cs while initializing the hub configuration:
public class Startup
{
public void Configuration(IAppBuilder app)
{
var idProvider = new CustomUserIdProvider();
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
Now, you can send message to a specific user using his userId
as mentioned in the documentation, like:
public class MyHub : Hub
{
public void Send(string userId, string message)
{
Clients.User(userId).send(message);
}
}
Hope this helps.
R cannot be resolved - Android error
This could be an issue caused by manually renaming the package in the AndroidManifest.xml
An alternative is to use the built in tool to rename the package, this will take care of most of the problems avoiding the R not found issue.
Right Click on the project
Click on Android Tools
Click on Rename Application Project
Enter the new package name
Then a pop-up will appear asking for changes to be applied, including the R workaround.
Source: Rename package name in android
C# Enum - How to Compare Value
You can use extension methods to do the same thing with less code.
public enum AccountType
{
Retailer = 1,
Customer = 2,
Manager = 3,
Employee = 4
}
static class AccountTypeMethods
{
public static bool IsRetailer(this AccountType ac)
{
return ac == AccountType.Retailer;
}
}
And to use:
if (userProfile.AccountType.isRetailer())
{
//your code
}
I would recommend to rename the AccountType
to Account
. It's not a name convention.
Slicing a dictionary
You should be iterating over the tuple and checking if the key is in the dict not the other way around, if you don't check if the key exists and it is not in the dict you are going to get a key error:
print({k:d[k] for k in l if k in d})
Some timings:
{k:d[k] for k in set(d).intersection(l)}
In [22]: %%timeit
l = xrange(100000)
{k:d[k] for k in l}
....:
100 loops, best of 3: 11.5 ms per loop
In [23]: %%timeit
l = xrange(100000)
{k:d[k] for k in set(d).intersection(l)}
....:
10 loops, best of 3: 20.4 ms per loop
In [24]: %%timeit
l = xrange(100000)
l = set(l)
{key: d[key] for key in d.viewkeys() & l}
....:
10 loops, best of 3: 24.7 ms per
In [25]: %%timeit
l = xrange(100000)
{k:d[k] for k in l if k in d}
....:
100 loops, best of 3: 17.9 ms per loop
I don't see how {k:d[k] for k in l}
is not readable or elegant and if all elements are in d then it is pretty efficient.
How can I use onItemSelected in Android?
For Kotlin and bindings the code is:
binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
TLS 1.2 in .NET Framework 4.0
There are two possible scenarios,
If your application runs on .net framework 4.5 or less, and you can easily deploy new code to the production then you can use of below solution.
You can add the below line of code before making the API call,
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // .NET 4.0
If you cannot deploy new code and you want to resolve the issue with the same code which is present in the production, then you have two options.
Option 1 :
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
then create a file with extension .reg
and install.
Note : This setting will apply at registry level and is applicable to all application present on that machine and if you want to restrict to only single application then you can use Option 2
Option 2 : This can be done by changing some configuration setting in config file.
You can add either in your config file.
<runtime>
<AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false"/>
</runtime>
or
<runtime>
<AppContextSwitchOverrides value="Switch.System.Net.DontEnableSystemDefaultTlsVersions=false"
</runtime>
Using Rsync include and exclude options to include directory and file by pattern
Here's my "teach a person to fish" answer:
Rsync's syntax is definitely non-intuitive, but it is worth understanding.
- First, use
-vvv
to see the debug info for rsync.
$ rsync -nr -vvv --include="**/file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/
[sender] hiding directory 1280000000 because of pattern *
[sender] hiding directory 1260000000 because of pattern *
[sender] hiding directory 1270000000 because of pattern *
The key concept here is that rsync applies the include/exclude patterns for each directory recursively. As soon as the first include/exclude is matched, the processing stops.
The first directory it evaluates is /Storage/uploads
. Storage/uploads
has 1280000000/, 1260000000/, 1270000000/
dirs/files. None of them match file_11*.jpg
to include. All of them match *
to exclude. So they are excluded, and rsync ends.
- The solution is to include all dirs (
*/
) first. Then the first dir component will be 1260000000/, 1270000000/, 1280000000/
since they match */
. The next dir component will be 1260000000/
. In 1260000000/
, file_11_00.jpg
matches --include="file_11*.jpg"
, so it is included. And so forth.
$ rsync -nrv --include='*/' --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/
./
1260000000/
1260000000/file_11_00.jpg
1260000000/file_11_01.jpg
1270000000/
1270000000/file_11_00.jpg
1270000000/file_11_01.jpg
1280000000/
1280000000/file_11_00.jpg
1280000000/file_11_01.jpg
https://download.samba.org/pub/rsync/rsync.1
What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?
getPathInfo()
gives the extra path information after the URI, used to access your Servlet, where as getRequestURI()
gives the complete URI.
I would have thought they would be different, given a Servlet must be configured with its own URI pattern in the first place; I don't think I've ever served a Servlet from root (/).
For example if Servlet 'Foo' is mapped to URI '/foo' then I would have thought the URI:
/foo/path/to/resource
Would result in:
RequestURI = /foo/path/to/resource
and
PathInfo = /path/to/resource
Set EditText cursor color
After a lot of time spent trying all these technique in a Dialog, I finally had this idea : attach the theme to the Dialog itself and not to the TextInputLayout.
<style name="AppTheme_Dialog" parent="Theme.AppCompat.Dialog">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorWhite</item>
<item name="colorAccent">@color/colorPrimary</item>
</style>
inside onCreate :
public class myDialog extends Dialog {
private Activity activity;
private someVars;
public PopupFeedBack(Activity activity){
super(activity, R.style.AppTheme_Dialog);
setContentView(R.layout.myView);
....}}
cheers :)
Why should a Java class implement comparable?
Comparable is used to compare instances of your class. We can compare instances from many ways that is why we need to implement a method compareTo
in order to know how (attributes) we want to compare instances.
Dog
class:
package test;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog("brutus");
Dog d2 = new Dog("medor");
Dog d3 = new Dog("ara");
Dog[] dogs = new Dog[3];
dogs[0] = d1;
dogs[1] = d2;
dogs[2] = d3;
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* brutus
* medor
* ara
*/
Arrays.sort(dogs, Dog.NameComparator);
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* ara
* medor
* brutus
*/
}
}
Main
class:
package test;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog("brutus");
Dog d2 = new Dog("medor");
Dog d3 = new Dog("ara");
Dog[] dogs = new Dog[3];
dogs[0] = d1;
dogs[1] = d2;
dogs[2] = d3;
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* brutus
* medor
* ara
*/
Arrays.sort(dogs, Dog.NameComparator);
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* ara
* medor
* brutus
*/
}
}
Here is a good example how to use comparable in Java:
http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html?page=2
How can I make a time delay in Python?
import time
time.sleep(5) # Delays for 5 seconds. You can also use a float value.
Here is another example where something is run approximately once a minute:
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).
Interface vs Base class
Make a list of the things your objects must be, have, or do and the things your objects can (or might) be, have, or do. Must indicates your base types and can indicates your interfaces.
E.g., your PetBase must Breathe, and your IPet might DoTricks.
Analysis of your problem domain will help you define the precise hierarchy structure.
Java double comparison epsilon
Yes. Java doubles will hold their precision better than your given epsilon of 0.00001.
Any rounding error that occurs due to the storage of floating point values will occur smaller than 0.00001. I regularly use 1E-6
or 0.000001 for a double epsilon in Java with no trouble.
On a related note, I like the format of epsilon = 1E-5;
because I feel it is more readable (1E-5 in Java = 1 x 10^-5). 1E-6 is easy to distinguish from 1E-5 when reading code whereas 0.00001 and 0.000001 look so similar when glancing at code I think they are the same value.
Integer to hex string in C++
For those of you who figured out that many/most of the ios::fmtflags
don't work with std::stringstream
yet like the template idea that Kornel posted way back when, the following works and is relatively clean:
#include <iomanip>
#include <sstream>
template< typename T >
std::string hexify(T i)
{
std::stringbuf buf;
std::ostream os(&buf);
os << "0x" << std::setfill('0') << std::setw(sizeof(T) * 2)
<< std::hex << i;
return buf.str().c_str();
}
int someNumber = 314159265;
std::string hexified = hexify< int >(someNumber);
The way to check a HDFS directory's size?
When trying to calculate the total of a particular group of files within a directory the -s
option does not work (in Hadoop 2.7.1). For example:
Directory structure:
some_dir
+abc.txt
+count1.txt
+count2.txt
+def.txt
Assume each file is 1 KB in size. You can summarize the entire directory with:
hdfs dfs -du -s some_dir
4096 some_dir
However, if I want the sum of all files containing "count" the command falls short.
hdfs dfs -du -s some_dir/count*
1024 some_dir/count1.txt
1024 some_dir/count2.txt
To get around this I usually pass the output through awk.
hdfs dfs -du some_dir/count* | awk '{ total+=$1 } END { print total }'
2048
SQL "select where not in subquery" returns no results
I had an example where I was looking up and because one table held the value as a double, the other as a string, they would not match (or not match without a cast). But only NOT IN. As SELECT ... IN ... worked. Weird, but thought I would share in case anyone else encounters this simple fix.
OperationalError, no such column. Django
I think you skipped this steps...run the following commands to see if you had forgotten to execute them...it worked for me.
$ python manage.py makemigrations
$ python manage.py migrate
Thank you.
Write a mode method in Java to find the most frequently occurring element in an array
You should be able to do this in N operations, meaning in just one pass, O(n) time.
Use a map or int[] (if the problem is only for ints) to increment the counters, and also use a variable that keeps the key which has the max count seen. Everytime you increment a counter, ask what the value is and compare it to the key you used last, if the value is bigger update the key.
public class Mode {
public static int mode(final int[] n) {
int maxKey = 0;
int maxCounts = 0;
int[] counts = new int[n.length];
for (int i=0; i < n.length; i++) {
counts[n[i]]++;
if (maxCounts < counts[n[i]]) {
maxCounts = counts[n[i]];
maxKey = n[i];
}
}
return maxKey;
}
public static void main(String[] args) {
int[] n = new int[] { 3,7,4,1,3,8,9,3,7,1 };
System.out.println(mode(n));
}
}
Determine the path of the executing BASH script
For the relative path (i.e. the direct equivalent of Windows' %~dp0
):
MY_PATH="`dirname \"$0\"`"
echo "$MY_PATH"
For the absolute, normalized path:
MY_PATH="`dirname \"$0\"`" # relative
MY_PATH="`( cd \"$MY_PATH\" && pwd )`" # absolutized and normalized
if [ -z "$MY_PATH" ] ; then
# error; for some reason, the path is not accessible
# to the script (e.g. permissions re-evaled after suid)
exit 1 # fail
fi
echo "$MY_PATH"
Excel - Combine multiple columns into one column
Try this. Click anywhere in your range of data and then use this macro:
Sub CombineColumns()
Dim rng As Range
Dim iCol As Integer
Dim lastCell As Integer
Set rng = ActiveCell.CurrentRegion
lastCell = rng.Columns(1).Rows.Count + 1
For iCol = 2 To rng.Columns.Count
Range(Cells(1, iCol), Cells(rng.Columns(iCol).Rows.Count, iCol)).Cut
ActiveSheet.Paste Destination:=Cells(lastCell, 1)
lastCell = lastCell + rng.Columns(iCol).Rows.Count
Next iCol
End Sub
Breaking out of a nested loop
Sometimes nice to abstract the code into it's own function and than use an early return - early returns are evil though : )
public void GetIndexOf(Transform transform, out int outX, out int outY)
{
outX = -1;
outY = -1;
for (int x = 0; x < Columns.Length; x++)
{
var column = Columns[x];
for (int y = 0; y < column.Transforms.Length; y++)
{
if(column.Transforms[y] == transform)
{
outX = x;
outY = y;
return;
}
}
}
}
How to get substring from string in c#?
string text = "Retrieves a substring from this instance. The substring starts at a specified character position. Some other text";
string result = text.Substring(text.IndexOf('.') + 1,text.LastIndexOf('.')-text.IndexOf('.'))
This will cut the part of string which lays between the special characters.
How do I close a tkinter window?
You can use:
root.destroy()
Or
root.quit()
If that does not work, change root to what ever your variable was at the start of your program
import tkinter
main = Tk()
main.destroy()
main.mainloop
Dump a list in a pickle file and retrieve it back later
Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.
So, first build a list, then use pickle.dump
to send it to a file...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
>>> import pickle
>>>
>>> with open('parrot.pkl', 'wb') as f:
... pickle.dump(mylist, f)
...
>>>
Then quit and come back later… and open with pickle.load
...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
... mynewlist = pickle.load(f)
...
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
What are the file limits in Git (number and size)?
I think that it's good to try to avoid large file commits as being part of the repository (e.g. a database dump might be better off elsewhere), but if one considers the size of the kernel in its repository, you can probably expect to work comfortably with anything smaller in size and less complex than that.
Use RSA private key to generate public key?
here in this code first we are creating RSA key which is private but it has pair of its public key as well so to get your actual public key we simply do this
openssl rsa -in mykey.pem -pubout > mykey.pub
hope you get it for more info check this
Constructors in Go
In Go, a constructor can be implemented using a function that returns a pointer to a modified structure.
type Colors struct {
R byte
G byte
B byte
}
// Constructor
func NewColors (r, g, b byte) *Colors {
return &Color{R:r, G:g, B:b}
}
For weak dependencies and better abstraction, the constructor does not return a pointer to a structure, but an interface that this structure implements.
type Painter interface {
paintMethod1() byte
paintMethod2(byte) byte
}
type Colors struct {
R byte
G byte
B byte
}
// Constructor return intreface
func NewColors(r, g, b byte) Painter {
return &Color{R: r, G: g, B: b}
}
func (c *Colors) paintMethod1() byte {
return c.R
}
func (c *Colors) paintMethod2(b byte) byte {
return c.B = b
}
Pandas: convert dtype 'object' to int
Follow these steps:
1.clean your file -> open your datafile in csv
format and see that there is "?" in place of empty places and delete all of them.
2.drop the rows containing missing values
e.g.:
df.dropna(subset=["normalized-losses"], axis = 0 , inplace= True)
3.use astype now for conversion
df["normalized-losses"]=df["normalized-losses"].astype(int)
Note: If still finding erros in your program then again inspect your csv
file, open it in excel to find whether is there an "?" in your required column, then delete it and save file and go back and run your program.
comment success! if it works. :)
How can I delete one element from an array by value
You can also monkey patch it. I never understood why Ruby has an except
method for Hash
but not for Array
:
class Array
def except value
value = value.kind_of(Array) ? value : [value]
self - value
end
end
Now you can do:
[1,3,7,"436",354,nil].except(354) #=> [1,3,7,"436",nil]
Or:
[1,3,7,"436",354,nil].except([354, 1]) #=> [3,7,"436",nil]
Finding the index of elements based on a condition using python list comprehension
Even if it's a late answer: I think this is still a very good question and IMHO Python (without additional libraries or toolkits like numpy) is still lacking a convenient method to access the indices of list elements according to a manually defined filter.
You could manually define a function, which provides that functionality:
def indices(list, filtr=lambda x: bool(x)):
return [i for i,x in enumerate(list) if filtr(x)]
print(indices([1,0,3,5,1], lambda x: x==1))
Yields: [0, 4]
In my imagination the perfect way would be making a child class of list and adding the indices function as class method. In this way only the filter method would be needed:
class MyList(list):
def __init__(self, *args):
list.__init__(self, *args)
def indices(self, filtr=lambda x: bool(x)):
return [i for i,x in enumerate(self) if filtr(x)]
my_list = MyList([1,0,3,5,1])
my_list.indices(lambda x: x==1)
I elaborated a bit more on that topic here:
http://tinyurl.com/jajrr87
How to pass List from Controller to View in MVC 3
Create a model which contains your list and other things you need for the view.
For example:
public class MyModel
{
public List<string> _MyList { get; set; }
}
From the action method put your desired list to the Model, _MyList
property, like:
public ActionResult ArticleList(MyModel model)
{
model._MyList = new List<string>{"item1","item2","item3"};
return PartialView(@"~/Views/Home/MyView.cshtml", model);
}
In your view access the model as follows
@model MyModel
foreach (var item in Model)
{
<div>@item</div>
}
I think it will help for start.
.gitignore all the .DS_Store files in every folder and subfolder
You should add following lines while creating a project. It will always ignore .DS_Store
to be pushed to the repository.
*.DS_Store
this will ignore .DS_Store while code commit.
git rm --cached .DS_Store
this is to remove .DS_Store files from your repository, in case you need it, you can uncomment it.
## ignore .DS_Store file.
# git rm --cached .DS_Store
*.DS_Store
Can I delete data from the iOS DeviceSupport directory?
Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging.
If you don't need to support those devices any more, you can delete the directory without ill effect
PostgreSQL: Why psql can't connect to server?
In my case I had this error, /var/run/postgresql/.s.PGSQL.5433
(note, one number up from the file it was looking for, .s.PGSQL.5432
) was present. Tried the instructions at the top of this page but nothing worked.
Turns out there was an old directory for PostGreSQL 12 config files in /etc/postgresql/12
, which I deleted, which solved the issue.
How to click on hidden element in Selenium WebDriver?
First store that element in object, let's say element
and then write following code to click on that hidden element:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);
Android Studio-No Module
I had the same issue since I changed my app ID in config.xml file.
I used to open my Android project by choosing among recent projects of Android Studio.
I just File > Open > My project to get it working again.
How do I stretch a background image to cover the entire HTML element?
You cannot in pure CSS. Having an image covering the whole page behind all other components is probably your best bet (looks like that's the solution given above). Anyway, chances are it will look awful anyway. I would try either an image big enough to cover most screen resolutions (say up to 1600x1200, above it is scarcer), to limit the width of the page, or just to use an image that tile.
Search of table names
I'm using this and works fine
SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%%'
Add/delete row from a table
Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.
Open source PDF library for C/C++ application?
It depends a bit on your needs. Some toolkits are better at drawing, others are better for writing text. Cairo has a pretty good for drawing (it support a wide range of screen and file types, including pdf), but it may not be ideal for good typography.
How to use range-based for() loop with std::map?
Each element of the container is a map<K, V>::value_type
, which is a typedef
for std::pair<const K, V>
. Consequently, in C++17 or higher, you can write
for (auto& [key, value]: myMap) {
std::cout << key << " has value " << value << std::endl;
}
or as
for (const auto& [key, value]: myMap) {
std::cout << key << " has value " << value << std::endl;
}
if you don't plan on modifying the values.
In C++11 and C++14, you can use enhanced for
loops to extract out each pair on its own, then manually extract the keys and values:
for (const auto& kv : myMap) {
std::cout << kv.first << " has value " << kv.second << std::endl;
}
You could also consider marking the kv
variable const
if you want a read-only view of the values.
How can I add some small utility functions to my AngularJS application?
Do I understand correctly that you just want to define some utility methods and make them available in templates?
You don't have to add them to every controller. Just define a single controller for all the utility methods and attach that controller to <html> or <body> (using the ngController directive). Any other controllers you attach anywhere under <html> (meaning anywhere, period) or <body> (anywhere but <head>) will inherit that $scope and will have access to those methods.
g++ undefined reference to typeinfo
This can also happen when you mix -fno-rtti
and -frtti
code. Then you need to ensure that any class, which type_info
is accessed in the -frtti
code, have their key method compiled with -frtti
. Such access can happen when you create an object of the class, use dynamic_cast
etc.
[source]