The formula provided by Blake doesn't seem to work for me. For past dates it returns due in xx days and for future dates, it returns overdue. Also, it will only return 15 days overdue, when it could actually be 30, 60 90+.
I created this, which seems to work and provides 'Due in xx days', 'Overdue xx days' and 'Due Today'.
=IF(ISBLANK(O10),"",IF(DAYS(TODAY(),O10)<0,CONCATENATE("Due in ",-DAYS(TODAY(),O10)," Days"),IF(DAYS(TODAY(),O10)>0,CONCATENATE("Overdue ",DAYS(TODAY(),O10)," Days"),"Due Today")))
Add some padding to allow a leading zero - where needed - and concatenate using your delimiter of choice as string.
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date(my_date);
var dformatted = [(d.getMonth()+1).padLeft(), d.getDate().padLeft(), d.getFullYear()].join('/');
Step 1:
CREATE TABLE [DBO].T_EMPLOYEES_DETAILS ( Id int, Name nvarchar(50), Gender nvarchar(10), Salary int )
Step 2:
CREATE TYPE EmpInsertType AS TABLE ( Id int, Name nvarchar(50), Gender nvarchar(10), Salary int )
Step 3:
/* Must add READONLY keyword at end of the variable */
CREATE PROC PRC_EmpInsertType @EmployeeInsertType EmpInsertType READONLY AS BEGIN INSERT INTO [DBO].T_EMPLOYEES_DETAILS SELECT * FROM @EmployeeInsertType END
Step 4:
DECLARE @EmployeeInsertType EmpInsertType
INSERT INTO @EmployeeInsertType VALUES(1,'John','Male',50000) INSERT INTO @EmployeeInsertType VALUES(2,'Praveen','Male',60000) INSERT INTO @EmployeeInsertType VALUES(3,'Chitra','Female',45000) INSERT INTO @EmployeeInsertType VALUES(4,'Mathy','Female',6600) INSERT INTO @EmployeeInsertType VALUES(5,'Sam','Male',50000)
EXEC PRC_EmpInsertType @EmployeeInsertType
=======================================
SELECT * FROM T_EMPLOYEES_DETAILS
OUTPUT
1 John Male 50000
2 Praveen Male 60000
3 Chitra Female 45000
4 Mathy Female 6600
5 Sam Male 50000
I found a post suggesting a solution for that. It's about to run:
svn resolve --accept working <YourPath>
which will claim the local version files as OK.
You can run it for single file or entire project catalogues.
One place where I use @import is when I'm doing two versions of a page, English and French. I'll build out my page in English, using a main.css. When I build out the French version, I'll link to a French stylesheet (main_fr.css). At the top of the French stylesheet, I'll import the main.css, and then redefine specific rules for just the parts I need different in the French version.
I know I am late, but what worked for me (total git newbie) was executing the following set of git commands:
git rm -r --cached .
git add .
git commit -am "Remove ignored files and resubmitting files
To give credit where it is due, here is the link to the source.
Python has a ternary form for assignments; however there may be even a shorter form that people should be aware of.
It's very common to need to assign to a variable one value or another depending on a condition.
>>> li1 = None
>>> li2 = [1, 2, 3]
>>>
>>> if li1:
... a = li1
... else:
... a = li2
...
>>> a
[1, 2, 3]
^ This is the long form for doing such assignments.
Below is the ternary form. But this isn't most succinct way - see last example.
>>> a = li1 if li1 else li2
>>>
>>> a
[1, 2, 3]
>>>
With Python, you can simply use or
for alternative assignments.
>>> a = li1 or li2
>>>
>>> a
[1, 2, 3]
>>>
The above works since li1
is None
and the interp treats that as False in logic expressions. The interp then moves on and evaluates the second expression, which is not None
and it's not an empty list - so it gets assigned to a.
This also works with empty lists. For instance, if you want to assign a
whichever list has items.
>>> li1 = []
>>> li2 = [1, 2, 3]
>>>
>>> a = li1 or li2
>>>
>>> a
[1, 2, 3]
>>>
Knowing this, you can simply such assignments whenever you encounter them. This also works with strings and other iterables. You could assign a
whichever string isn't empty.
>>> s1 = ''
>>> s2 = 'hello world'
>>>
>>> a = s1 or s2
>>>
>>> a
'hello world'
>>>
I always liked the C ternary syntax, but Python takes it a step further!
I understand that some may say this isn't a good stylistic choice because it relies on mechanics that aren't immediately apparent to all developers. I personally disagree with that viewpoint. Python is a syntax rich language with lots of idiomatic tricks that aren't immediately apparent to the dabler. But the more you learn and understand the mechanics of the underlying system, the more you appreciate it.
Locations are evaluated in this order:
location = /path/file.ext {}
Exact matchlocation ^~ /path/ {}
Priority prefix match -> longest firstlocation ~ /Paths?/ {}
(case-sensitive regexp) and location ~* /paths?/ {}
(case-insensitive regexp) -> first matchlocation /path/ {}
Prefix match -> longest firstThe priority prefix match (number 2) is exactly as the common prefix match (number 4), but has priority over any regexp.
For both prefix matche types the longest match wins.
Case-sensitive and case-insensitive have the same priority. Evaluation stops at the first matching rule.
Documentation says that all prefix rules are evaluated before any regexp, but if one regexp matches then no standard prefix rule is used. That's a little bit confusing and does not change anything for the priority order reported above.
This happened to me when deleting some Equinox package from my plugins
directory, make sure this is not the case.
If you are on Linux, gitg
is way to go to do it very quickly and graphically.
If you insist on command line you can use:
git log --oneline --decorate
To make git log
nicer by default, I typically set these global preferences:
git config --global log.decorate true
git config --global log.abbrevCommit true
The main purpose of the interfaces is that it makes a contract between you and any other class that implement that interface which makes your code decoupled and allows expandability.
Since all the players are numbered I would just use an ArrayList<Player>()
Something like
List<Player> players = new ArrayList<Player>();
System.out.printf("Give the number of the players ");
int number_of_players = scanner.nextInt();
scanner.nextLine(); // discard the rest of the line.
for(int k = 0;k < number_of_players; k++){
System.out.printf("Give the name of player %d: ", k + 1);
String name_of_player = scanner.nextLine();
players.add(new Player(name_of_player,0)); //k=id and 0=score
}
for(Player player: players) {
System.out.println("Name of player in this round:" + player.getName());
As a not yet fully standardized solution (though in alignment with the color syntax in CSS3) you can use e.g fill="rgba(124,240,10,0.5)"
. Works fine in Firefox, Opera, Chrome.
Related answer, but if you want to run clean up a user inputting values into a form, here's what you can do:
const numFormatter = new Intl.NumberFormat('en-US', {
style: "decimal",
maximumFractionDigits: 2
})
// Good Inputs
parseFloat(numFormatter.format('1234').replace(/,/g,"")) // 1234
parseFloat(numFormatter.format('123').replace(/,/g,"")) // 123
// 3rd decimal place rounds to nearest
parseFloat(numFormatter.format('1234.233').replace(/,/g,"")); // 1234.23
parseFloat(numFormatter.format('1234.239').replace(/,/g,"")); // 1234.24
// Bad Inputs
parseFloat(numFormatter.format('1234.233a').replace(/,/g,"")); // NaN
parseFloat(numFormatter.format('$1234.23').replace(/,/g,"")); // NaN
// Edge Cases
parseFloat(numFormatter.format(true).replace(/,/g,"")) // 1
parseFloat(numFormatter.format(false).replace(/,/g,"")) // 0
parseFloat(numFormatter.format(NaN).replace(/,/g,"")) // NaN
Use the international date local via format
. This cleans up any bad inputs, if there is one it returns a string of NaN
you can check for. There's no way currently of removing commas as part of the locale (as of 10/12/19), so you can use a regex command to remove commas using replace
.
ParseFloat
converts the this type definition from string to number
If you use React, this is what your calculate function could look like:
updateCalculationInput = (e) => {
let value;
value = numFormatter.format(e.target.value); // 123,456.78 - 3rd decimal rounds to nearest number as expected
if(value === 'NaN') return; // locale returns string of NaN if fail
value = value.replace(/,/g, ""); // remove commas
value = parseFloat(value); // now parse to float should always be clean input
// Do the actual math and setState calls here
}
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
The example on the Python docs is quite straightforward:
groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
So in your case, data is a list of nodes, keyfunc
is where the logic of your criteria function goes and then groupby()
groups the data.
You must be careful to sort the data by the criteria before you call groupby
or it won't work. groupby
method actually just iterates through a list and whenever the key changes it creates a new group.
Use HttpClient to grab the contents of the URL. And then use the library from json.org to parse the JSON. I've used these two libraries on many projects and they have been robust and simple to use.
Other than that you can try using a Facebook API java library. I don't have any experience in this area, but there is a question on stack overflow related to using a Facebook API in java. You may want to look at RestFB as a good choice for a library to use.
We will have to use git cherry-pick <commit-number>
Scenario: I am on a branch called release and I want to add only few changes from master branch to release branch.
Step 1: checkout the branch where you want to add the changes
git checkout release
Step 2: get the commit number of the changes u want to add
for example
git cherry-pick 634af7b56ec
Step 3: git push
Note: Every time your merge there is a separate commit number create. Do not take the commit number for merge that won't work. Instead, the commit number for any regular commit u want to add.
Doxygen creates inheritance diagrams but I dont think it will create an entire class hierachy. It does allow you to use the GraphViz tool. If you use the Doxygen GUI frontend tool you will find the relevant options in Step2: -> Wizard tab -> Diagrams
. The DOT relation options are under the Expert Tab.
One trick is to turn on the rewrite log. To turn it on, try this line in your apache main config or current virtual host file (not in .htaccess
):
LogLevel alert rewrite:trace6
Before Apache httpd 2.4 mod_rewrite, such a per-module logging configuration did not exist yet, instead you could use the following logging settings:
RewriteEngine On
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3
For those who are already familiar with setting up a RecyclerView
to make a list, the good news is that making a grid is largely the same. You just use a GridLayoutManager
instead of a LinearLayoutManager
when you set the RecyclerView
up.
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
If you need more help than that, then check out the following example.
The following is a minimal example that will look like the image below.
Start with an empty activity. You will perform the following tasks to add the RecyclerView
grid. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.
Make sure the following dependencies are in your app gradle.build
file:
compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'
You can update the version numbers to whatever is the most current.
Add the RecyclerView
to your xml layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/rvNumbers"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Each cell in our RecyclerView
grid is only going to have a single TextView
. Create a new layout resource file.
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:padding="5dp"
android:layout_width="50dp"
android:layout_height="50dp">
<TextView
android:id="@+id/info_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@color/colorAccent"/>
</LinearLayout>
The RecyclerView
needs an adapter to populate the views in each cell with your data. Create a new java file.
MyRecyclerViewAdapter.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private String[] mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
MyRecyclerViewAdapter(Context context, String[] data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.myTextView.setText(mData[position]);
}
// total number of cells
@Override
public int getItemCount() {
return mData.length;
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.info_text);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return mData[id];
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Notes
GridView
and is a common need. You can remove this code if you don't need it.Add the following code to your main activity.
MainActivity.java
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvNumbers);
int numberOfColumns = 6;
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
adapter = new MyRecyclerViewAdapter(this, data);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position) {
Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position);
}
}
Notes
ItemClickListener
that we defined in our adapter. This allows us to handle cell click events in onItemClick
.That's it. You should be able to run your project now and get something similar to the image at the top.
Rounded corners
Auto-fitting columns
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
You can do this way -
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.
List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsList.Add(value);
}
// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();
Here's my non-silly example, (from Stevens APITUE) for Unix system calls which may be interrupted by a signal.
restart:
if (system_call() == -1) {
if (errno == EINTR) goto restart;
// handle real errors
}
The alternative is a degenerate loop. This version reads like English "if the system call was interrupted by a signal, restart it".
The other answers here fail to spell out a full solution for regex versions which don't support non-greedy matching. The greedy quantifiers (.*?
, .+?
etc) are a Perl 5 extension which isn't supported in traditional regular expressions.
If your stopping condition is a single character, the solution is easy; instead of
a(.*?)b
you can match
a[^ab]*b
i.e specify a character class which excludes the starting and ending delimiiters.
In the more general case, you can painstakingly construct an expression like
start(|[^e]|e(|[^n]|n(|[^d])))end
to capture a match between start
and the first occurrence of end
. Notice how the subexpression with nested parentheses spells out a number of alternatives which between them allow e
only if it isn't followed by nd
and so forth, and also take care to cover the empty string as one alternative which doesn't match whatever is disallowed at that particular point.
Of course, the correct approach in most cases is to use a proper parser for the format you are trying to parse, but sometimes, maybe one isn't available, or maybe the specialized tool you are using is insisting on a regular expression and nothing else.
You can use:
import random
random.choice(range(n))
or:
random.choice(range(1,n+1))
if you want it from 1
to n
and not from 0
.
Just a supplement here.
The following question is that what if I want more subplots in the figure?
As mentioned in the Doc, we can use fig = plt.subplots(nrows=2, ncols=2)
to set a group of subplots with grid(2,2) in one figure object.
Then as we know, the fig, ax = plt.subplots()
returns a tuple, let's try fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2)
firstly.
ValueError: not enough values to unpack (expected 4, got 2)
It raises a error, but no worry, because we now see that plt.subplots()
actually returns a tuple with two elements. The 1st one must be a figure object, and the other one should be a group of subplots objects.
So let's try this again:
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)
and check the type:
type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>
Of course, if you use parameters as (nrows=1, ncols=4), then the format should be:
fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)
So just remember to keep the construction of the list as the same as the subplots grid we set in the figure.
Hope this would be helpful for you.
Usage:
select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');
Function:
CREATE OR REPLACE FUNCTION
replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR)
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN
SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY'
AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;
EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name ||
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';
RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;
END;
$$ LANGUAGE plpgsql;
Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.
For Firefox, Chrome and Safari, nothing happens.
For IE the border is applied outside the checkbox (not as part of the checkbox), and the "fancy" shading effect in the checkbox is gone (displayed as an oldfashioned checkbox).
For Opera the border style is actually applying the border on the checkbox element.
Opera also handles other stylings on the checkbox better than other browsers: color is applied as the color of the tick, background-color is applied as background color inside the checkbox (IE applies the background as if the checkbox was inside a <div>
with background)).
The easiest solution is to wrap the checkbox inside a <div>
like others have suggested.
If you want to completely control the appearance you will have to go with the advanced image/javascript approach, also meantiond by others.
First off, (though this won't change the performance at all) consider cleaning up your code, similar to this:
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)]
fig.show()
tstart = time.time()
for i in xrange(1, 20):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
fig.canvas.draw()
print 'FPS:' , 20/(time.time()-tstart)
With the above example, I get around 10fps.
Just a quick note, depending on your exact use case, matplotlib may not be a great choice. It's oriented towards publication-quality figures, not real-time display.
However, there are a lot of things you can do to speed this example up.
There are two main reasons why this is as slow as it is.
1) Calling fig.canvas.draw()
redraws everything. It's your bottleneck. In your case, you don't need to re-draw things like the axes boundaries, tick labels, etc.
2) In your case, there are a lot of subplots with a lot of tick labels. These take a long time to draw.
Both these can be fixed by using blitting.
To do blitting efficiently, you'll have to use backend-specific code. In practice, if you're really worried about smooth animations, you're usually embedding matplotlib plots in some sort of gui toolkit, anyway, so this isn't much of an issue.
However, without knowing a bit more about what you're doing, I can't help you there.
Nonetheless, there is a gui-neutral way of doing it that is still reasonably fast.
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
fig.show()
# We need to draw the canvas before we start animating...
fig.canvas.draw()
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]
tstart = time.time()
for i in xrange(1, 2000):
items = enumerate(zip(lines, axes, backgrounds), start=1)
for j, (line, ax, background) in items:
fig.canvas.restore_region(background)
line.set_ydata(np.sin(j*x + i/10.0))
ax.draw_artist(line)
fig.canvas.blit(ax.bbox)
print 'FPS:' , 2000/(time.time()-tstart)
This gives me ~200fps.
To make this a bit more convenient, there's an animations
module in recent versions of matplotlib.
As an example:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
def animate(i):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
return lines
# We'd normally specify a reasonable "interval" here...
ani = animation.FuncAnimation(fig, animate, xrange(1, 200),
interval=0, blit=True)
plt.show()
Here is a version I came up with if you want to style words or individual characters at their index in react/javascript.
replaceAt( yourArrayOfIndexes, yourString/orArrayOfStrings )
Working example: https://codesandbox.io/s/ov7zxp9mjq
function replaceAt(indexArray, [...string]) {
const replaceValue = i => string[i] = <b>{string[i]}</b>;
indexArray.forEach(replaceValue);
return string;
}
And here is another alternate method
function replaceAt(indexArray, [...string]) {
const startTag = '<b>';
const endTag = '</b>';
const tagLetter = i => string.splice(i, 1, startTag + string[i] + endTag);
indexArray.forEach(tagLetter);
return string.join('');
}
And another...
function replaceAt(indexArray, [...string]) {
for (let i = 0; i < indexArray.length; i++) {
string = Object.assign(string, {
[indexArray[i]]: <b>{string[indexArray[i]]}</b>
});
}
return string;
}
You could try lattice:
require(lattice)
x <- 1:100000
y <- 1:100000
xyplot(y~x, scales=list(x = list(log = 10)), type="l")
The answer is short: alert(arguments.callee.name);
Simplest way? It works. :)
Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
Try
Using connection As New SqlConnection(ConnStrg)
connection.Open()
Dim command As New SqlCommand(queryString, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim DTResults As New DataTable
DTResults.Load(reader)
MsgBox(DTResults.Rows(0)(0).ToString)
End Using
Catch ex As Exception
MessageBox.Show("Error while executing .. " & ex.Message, "")
Finally
End Try
Using Python 3 you can have both required and non-required keyword arguments:
Optional: (default value defined for param 'b')
def func1(a, *, b=42):
...
func1(value_for_a) # b is optional and will default to 42
Required (no default value defined for param 'b'):
def func2(a, *, b):
...
func2(value_for_a, b=21) # b is set to 21 by the function call
func2(value_for_a) # ERROR: missing 1 required keyword-only argument: 'b'`
This can help in cases where you have many similar arguments next to each other especially if they are of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.
After having no success trying all the answers I managed to turn my mobile scroll off by simply adding:
html,
body {
overflow-x: hidden;
height: 100%;
}
body {
position: relative;
}
Its important to use %
not vh
for this. The height: 100%
was something I had been missing all along, crazy.
Using os.path.split
or os.path.basename
as others suggest won't work in all cases: if you're running the script on Linux and attempt to process a classic windows-style path, it will fail.
Windows paths can use either backslash or forward slash as path separator. Therefore, the ntpath
module (which is equivalent to os.path when running on windows) will work for all(1) paths on all platforms.
import ntpath
ntpath.basename("a/b/c")
Of course, if the file ends with a slash, the basename will be empty, so make your own function to deal with it:
def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
Verification:
>>> paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c',
... 'a/b/../../a/b/c/', 'a/b/../../a/b/c']
>>> [path_leaf(path) for path in paths]
['c', 'c', 'c', 'c', 'c', 'c', 'c']
(1) There's one caveat: Linux filenames may contain backslashes. So on linux, r'a/b\c'
always refers to the file b\c
in the a
folder, while on Windows, it always refers to the c
file in the b
subfolder of the a
folder. So when both forward and backward slashes are used in a path, you need to know the associated platform to be able to interpret it correctly. In practice it's usually safe to assume it's a windows path since backslashes are seldom used in Linux filenames, but keep this in mind when you code so you don't create accidental security holes.
In addition to the missing quotes around 100Mb
in the last else
, you also want to quote the constants in your if-statements if tSizeAns == "1":
, because raw_input
returns a string, which in comparison with an integer will always return false.
However the missing quotes are not the reason for the particular error message, because it would result in an syntax error before execution. Please check your posted code. I cannot reproduce the error message.
Also if ... elif ... else
in the way you use it is basically equivalent to a case
or switch
in other languages and is neither less readable nor much longer. It is fine to use here. One other way that might be a good idea to use if you just want to assign a value based on another value is a dictionary lookup:
tSize = {"1": "100Mb", "2": "200Mb"}[tSizeAns]
This however does only work as long as tSizeAns
is guaranteed to be in the range of tSize
. Otherwise you would have to either catch the KeyError
exception or use a defaultdict:
lookup = {"1": "100Mb", "2": "200Mb"} try: tSize = lookup[tSizeAns] except KeyError: tSize = "100Mb"
or
from collections import defaultdict [...] lookup = defaultdict(lambda: "100Mb", {"1": "100Mb", "2": "200Mb"}) tSize = lookup[tSizeAns]
In your case I think these methods are not justified for two values. However you could use the dictionary to construct the initial output at the same time.
The following solution seems like a good option,
<label ng-repeat="fruit in fruits">
<input
type="checkbox"
ng-model="fruit.checked"
ng-value="true"
> {{fruit.fruitName}}
</label>
And in controller model value fruits
will be like this
$scope.fruits = [
{
"name": "apple",
"checked": true
},
{
"name": "orange"
},
{
"name": "grapes",
"checked": true
}
];
Have a look at the documentation. You can have a .env file which picks up the PUBLIC_URL
Although you should remember that what its used for -
You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application.
A wait
can be "woken up" by another thread calling notify
on the monitor which is being waited on whereas a sleep
cannot. Also a wait
(and notify
) must happen in a block synchronized
on the monitor object whereas sleep
does not:
Object mon = ...;
synchronized (mon) {
mon.wait();
}
At this point the currently executing thread waits and releases the monitor. Another thread may do
synchronized (mon) { mon.notify(); }
(on the same mon
object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.
You can also call notifyAll
if more than one thread is waiting on the monitor – this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the wait
is in a synchronized
block) and carry on – the others will then be blocked until they can acquire the monitor's lock.
Another point is that you call wait
on Object
itself (i.e. you wait on an object's monitor) whereas you call sleep
on Thread
.
Yet another point is that you can get spurious wakeups from wait
(i.e. the thread which is waiting resumes for no apparent reason). You should always wait
whilst spinning on some condition as follows:
synchronized {
while (!condition) { mon.wait(); }
}
Just a note that the constant
keyword use for safe-area margins has been updated to env
for 11.2 beta+
https://webkit.org/blog/7929/designing-websites-for-iphone-x/
Try this:
SELECT CUSTOMER_ID, MAX(FIRSTNAME) AS FIRSTNAME, MAX(LASTNAME) AS LASTNAME ...
FROM
(
SELECT CUSTOMER_ID,
CASE WHEN DBCOLUMNNAME='FirstName' then DATA ELSE NULL END AS FIRSTNAME,
CASE WHEN DBCOLUMNNAME='LastName' then DATA ELSE NULL END AS LASTNAME,
... and so on ...
GROUP BY CUSTOMER_ID
) TEMP
GROUP BY CUSTOMER_ID
Variation of Aaron's answer. Using sed without temporary files
#!/bin/bash
VERSION=1.0.0
IMAGE=company/image
ID=$(docker build -t ${IMAGE} . | tail -1 | sed 's/.*Successfully built \(.*\)$/\1/')
docker tag ${ID} ${IMAGE}:${VERSION}
docker tag -f ${ID} ${IMAGE}:latest
Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!
// Test database connection
try {
DB::connection()->getPdo();
} catch (\Exception $e) {
die("Could not connect to the database. Please check your configuration. error:" . $e );
}
This will work for me:
.../xampp/htdocs/php/test.phtml
Try Linq:
Result = string.Join("", input.ToCharArray().Where(x=> ((int)x) < 127));
This will filter out all non ascii characters. Now if you want an equivalent, try the following:
Result = string.Join("", System.Text.Encoding.ASCII.GetChars(System.Text.Encoding.ASCII.GetBytes(input.ToCharArray())));
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
This works on IE7+, is standards compliant, and allows differing heights.
<style>
dt {
float: left;
clear: left;
width: 100px;
padding: 5px 0;
margin:0;
}
dd {
float: left;
width: 200px;
padding: 5px 0;
margin:0;
}
.cf:after {
content:'';
display:table;
clear:both;
}
</style>
<dl class="cf">
<dt>A</dt>
<dd>Apple</dd>
<dt>B</dt>
<dd>Banana<br>Bread<br>Bun</dd>
<dt>C</dt>
<dd>Cinnamon</dd>
</dl>
The pyplot functions you are calling, axhline()
and axvline()
draw lines that span a portion of the axis range, regardless of coordinates. The parameters xmin
or ymin
use value 0.0 as the minimum of the axis and 1.0 as the maximum of the axis.
Instead, use plt.plot((x1, x2), (y1, y2), 'k-')
to draw a line from the point (x1, y1) to the point (x2, y2) in color k. See pyplot.plot
.
Let me clarify two points here :
(a = 'b',c)
in function.
The correct order of defining parameter in function are :(a,b,c)
(a = 'b',r= 'j')
(*args)
(**kwargs)
def example(a, b, c=None, r="w" , d=[], *ae, **ab):
(a,b)
are positional parameter
(c=none)
is optional parameter
(r="w")
is keyword parameter
(d=[])
is list parameter
(*ae)
is keyword-only
(*ab)
is var-keyword parameter
so first re-arrange your parameters
so second remove this "len1 = hgt"
it's not allowed in python.
keep in mind the difference between argument and parameters.
On Ubuntu, you can set proxy by using
export http_proxy=http://username:password@proxy:port
export https_proxy=http://username:password@proxy:port
or if you are having SOCKS error use
export all_proxy=http://username:password@proxy:port
Then run pip
sudo -E pip3 install {packageName}
View the Inner Exception of the exception to get a more specific error message.
One way to view the Inner Exception would be to catch the exception, and put a breakpoint on it. Then in the Locals window: select the Exception variable > InnerException > Message
And/Or just write to console:
catch (Exception e)
{
Console.WriteLine(e.InnerException.Message);
}
How are you setting up the SqlParameter
? You should set the SqlDbType
property to SqlDbType.DateTime
and then pass the DateTime
directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then).
You should be able to get the value into the DB. If not, here is a very simple example of how to do it:
static void Main(string[] args)
{
// Create the connection.
using (SqlConnection connection = new SqlConnection(@"Data Source=..."))
{
// Open the connection.
connection.Open();
// Create the command.
using (SqlCommand command = new SqlCommand("xsp_Test", connection))
{
// Set the command type.
command.CommandType = System.Data.CommandType.StoredProcedure;
// Add the parameter.
SqlParameter parameter = command.Parameters.Add("@dt",
System.Data.SqlDbType.DateTime);
// Set the value.
parameter.Value = DateTime.Now;
// Make the call.
command.ExecuteNonQuery();
}
}
}
I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone.
If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the DateTime
, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the DateTime
struct will easily do).
All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the ToUniversalTime
method, not by converting to a string) to the stored procedure.
And when you get the value back, call the ToLocalTime
method to get the time in the local time zone.
Just an update.
If the ticked answer is working fine for you but it shows nothing when the search text is empty. Here is the solution:
private class ItemFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
if(constraint.length() == 0)
{
results.count = originalData.size();
results.values = originalData;
}else {
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
For any query comment below
If you are using Java 8 or newer you should definitely choose PKCS12
, the default since Java 9 (JEP 229).
The advantages compared to JKS
and JCEKS
are:
PKCS12
is a standard format, it can be read by other programs and libraries1JKS
and JCEKS
are pretty insecure. This can be seen by the number of tools for brute forcing passwords of these keystore types, especially popular among Android developers.2, 31 There is JDK-8202837, which has been fixed in Java 11
2 The iteration count for PBE used by all keystore types (including PKCS12) used to be rather weak (CVE-2017-10356), however this has been fixed in 9.0.1, 8u151, 7u161, and 6u171
3 For further reading:
atoi can do that for you
Example:
char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234
Double click the button in the form designer and write the code:
var form2 = new Form2();
form2.Show();
Search some samples on the Internet.
What you are looking for is a simple directive like:
location ~* \.(?:manifest|appcache|html?|xml|json)$ {
expires -1;
}
The above will not cache the extensions within the (). You can configure different directives for different file types.
The simplest way to extract a number from a string is to use regular expressions and findall
.
>>> import re
>>> s = '300 gm'
>>> re.findall('\d+', s)
['300']
>>> s = '300 gm 200 kgm some more stuff a number: 439843'
>>> re.findall('\d+', s)
['300', '200', '439843']
It might be that you need something more complex, but this is a good first step.
Note that you'll still have to call int
on the result to get a proper numeric type (rather than another string):
>>> map(int, re.findall('\d+', s))
[300, 200, 439843]
The difference between relational and non-relational is exactly that. The relational database architecture provides with constraints objects such as primary keys, foreign keys, etc that allows one to tie two or more tables in a relation. This is good so that we normalize our tables which is to say split information about what the database represents into many different tables, once can keep the integrity of the data.
For example, say you have a series of table that houses information about an employee. You could not delete a record from a table without deleting all the records that pertain to such record from the other tables. In this way you implement data integrity. The non-relational database doesn't provide this constraints constructs that will allow you to implement data integrity.
Unless you don't implement this constraint in the front end application that is utilized to populate the databases' tables, you are implementing a mess that can be compared with the wild west.
y.tolist().count(val)
with val 0 or 1
Since a python list has a native function count
, converting to list before using that function is a simple solution.
The sessions parameter is derived from the processes parameter and changes accordingly when you change the number of max processes. See the Oracle docs for further info.
To get only the info about the sessions:
select current_utilization, limit_value
from v$resource_limit
where resource_name='sessions';
CURRENT_UTILIZATION LIMIT_VALUE ------------------- ----------- 110 792
Try this to show info about both:
select resource_name, current_utilization, max_utilization, limit_value
from v$resource_limit
where resource_name in ('sessions', 'processes');
RESOURCE_NAME CURRENT_UTILIZATION MAX_UTILIZATION LIMIT_VALUE ------------- ------------------- --------------- ----------- processes 96 309 500 sessions 104 323 792
</script>
has to be broken up because otherwise it would end the enclosing <script></script>
block too early. Really it should be split between the <
and the /
, because a script block is supposed (according to SGML) to be terminated by any end-tag open (ETAGO) sequence (i.e. </
):
Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "
</
" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.
However in practice browsers only end parsing a CDATA script block on an actual </script>
close-tag.
In XHTML there is no such special handling for script blocks, so any <
(or &
) character inside them must be &escaped;
like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be:
<script type="text/javascript">
document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');
</script>
when should we use it
Quentin's answer is right: use multipart/form-data
if the form contains a file upload, and application/x-www-form-urlencoded
otherwise, which is the default if you omit enctype
.
I'm going to:
There are three possibilities for enctype
:
application/x-www-form-urlencoded
multipart/form-data
(spec points to RFC7578)text/plain
. This is "not reliably interpretable by computer", so it should never be used in production, and we will not look further into it.Once you see an example of each method, it becomes obvious how they work, and when you should use each one.
You can produce examples using:
nc -l
or an ECHO server: HTTP test server accepting GET/POST requestsSave the form to a minimal .html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>upload</title>
</head>
<body>
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text1" value="text default">
<p><input type="text" name="text2" value="aωb">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><input type="file" name="file3">
<p><button type="submit">Submit</button>
</form>
</body>
</html>
We set the default text value to aωb
, which means a?b
because ?
is U+03C9
, which are the bytes 61 CF 89 62
in UTF-8.
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
# Binary file containing 4 bytes: 'a', 1, 2 and 'b'.
printf 'a\xCF\x89b' > binary
Run our little echo server:
while true; do printf '' | nc -l 8000 localhost; done
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received.
Tested on: Ubuntu 14.04.3, nc
BSD 1.105, Firefox 40.
Firefox sent:
POST / HTTP/1.1
[[ Less interesting headers ... ]]
Content-Type: multipart/form-data; boundary=---------------------------735323031399963166993862150
Content-Length: 834
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="text1"
text default
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="text2"
a?b
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file3"; filename="binary"
Content-Type: application/octet-stream
a?b
-----------------------------735323031399963166993862150--
For the binary file and text field, the bytes 61 CF 89 62
(a?b
in UTF-8) are sent literally. You could verify that with nc -l localhost 8000 | hd
, which says that the bytes:
61 CF 89 62
were sent (61
== 'a' and 62
== 'b').
Therefore it is clear that:
Content-Type: multipart/form-data; boundary=---------------------------735323031399963166993862150
sets the content type to multipart/form-data
and says that the fields are separated by the given boundary
string.
But note that the:
boundary=---------------------------735323031399963166993862150
has two less dadhes --
than the actual barrier
-----------------------------735323031399963166993862150
This is because the standard requires the boundary to start with two dashes --
. The other dashes appear to be just how Firefox chose to implement the arbitrary boundary. RFC 7578 clearly mentions that those two leading dashes --
are required:
4.1. "Boundary" Parameter of multipart/form-data
As with other multipart types, the parts are delimited with a boundary delimiter, constructed using CRLF, "--", and the value of the "boundary" parameter.
every field gets some sub headers before its data: Content-Disposition: form-data;
, the field name
, the filename
, followed by the data.
The server reads the data until the next boundary string. The browser must choose a boundary that will not appear in any of the fields, so this is why the boundary may vary between requests.
Because we have the unique boundary, no encoding of the data is necessary: binary data is sent as is.
TODO: what is the optimal boundary size (log(N)
I bet), and name / running time of the algorithm that finds it? Asked at: https://cs.stackexchange.com/questions/39687/find-the-shortest-sequence-that-is-not-a-sub-sequence-of-a-set-of-sequences
Content-Type
is automatically determined by the browser.
How it is determined exactly was asked at: How is mime type of an uploaded file determined by browser?
Now change the enctype
to application/x-www-form-urlencoded
, reload the browser, and resubmit.
Firefox sent:
POST / HTTP/1.1
[[ Less interesting headers ... ]]
Content-Type: application/x-www-form-urlencoded
Content-Length: 51
text1=text+default&text2=a%CF%89b&file1=a.txt&file2=a.html&file3=binary
Clearly the file data was not sent, only the basenames. So this cannot be used for files.
As for the text field, we see that usual printable characters like a
and b
were sent in one byte, while non-printable ones like 0xCF
and 0x89
took up 3 bytes each: %CF%89
!
File uploads often contain lots of non-printable characters (e.g. images), while text forms almost never do.
From the examples we have seen that:
multipart/form-data
: adds a few bytes of boundary overhead to the message, and must spend some time calculating it, but sends each byte in one byte.
application/x-www-form-urlencoded
: has a single byte boundary per field (&
), but adds a linear overhead factor of 3x for every non-printable character.
Therefore, even if we could send files with application/x-www-form-urlencoded
, we wouldn't want to, because it is so inefficient.
But for printable characters found in text fields, it does not matter and generates less overhead, so we just use it.
Try the fat-jar extension. It will include all external jars inside the jar.
In your component.ts
import { Component } from '@angular/core';
@Component({
...
})
export class AppComponent {
...
goToSpecificUrl(url): void {
window.location.href=url;
}
gotoGoogle() : void {
window.location.href='https://www.google.com';
}
}
In your component.html
<button type="button" (click)="goToSpecificUrl('http://stackoverflow.com/')">Open URL</button>
<button type="button" (click)="gotoGoogle()">Open Google</button>
<li *ngFor="item of itemList" (click)="goToSpecificUrl(item.link)"> // (click) don't enable pointer when we hover so we should enable it by using css like: **cursor: pointer;**
Here, in this post you will find the detailed code for establishing socket between devices or between two application in the same mobile.
You have to create two application to test below code.
In both application's manifest file, add below permission
<uses-permission android:name="android.permission.INTERNET" />
1st App code: Client Socket
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:id="@+id/tr_send_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="11dp">
<EditText
android:id="@+id/edt_send_message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:hint="Enter message"
android:inputType="text" />
<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="Send" />
</TableRow>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/tr_send_message"
android:layout_marginTop="25dp"
android:id="@+id/scrollView2">
<TextView
android:id="@+id/tv_reply_from_server"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
</RelativeLayout>
MainActivity.java
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
/**
* Created by Girish Bhalerao on 5/4/2017.
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTextViewReplyFromServer;
private EditText mEditTextSendMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonSend = (Button) findViewById(R.id.btn_send);
mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message);
mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server);
buttonSend.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
sendMessage(mEditTextSendMessage.getText().toString());
break;
}
}
private void sendMessage(final String msg) {
final Handler handler = new Handler();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
//Replace below IP with the IP of that device in which server socket open.
//If you change port then change the port number in the server side code also.
Socket s = new Socket("xxx.xxx.xxx.xxx", 9002);
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(msg);
output.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
final String st = input.readLine();
handler.post(new Runnable() {
@Override
public void run() {
String s = mTextViewReplyFromServer.getText().toString();
if (st.trim().length() != 0)
mTextViewReplyFromServer.setText(s + "\nFrom Server : " + st);
}
});
output.close();
out.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
2nd App Code - Server Socket
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_stop_receiving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP Receiving data"
android:layout_alignParentTop="true"
android:enabled="false"
android:layout_centerHorizontal="true"
android:layout_marginTop="89dp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btn_stop_receiving"
android:layout_marginTop="35dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="@+id/tv_data_from_client"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
<Button
android:id="@+id/btn_start_receiving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="START Receiving data"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp" />
</RelativeLayout>
MainActivity.java
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Girish Bhalerao on 5/4/2017.
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
final Handler handler = new Handler();
private Button buttonStartReceiving;
private Button buttonStopReceiving;
private TextView textViewDataFromClient;
private boolean end = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStartReceiving = (Button) findViewById(R.id.btn_start_receiving);
buttonStopReceiving = (Button) findViewById(R.id.btn_stop_receiving);
textViewDataFromClient = (TextView) findViewById(R.id.tv_data_from_client);
buttonStartReceiving.setOnClickListener(this);
buttonStopReceiving.setOnClickListener(this);
}
private void startServerSocket() {
Thread thread = new Thread(new Runnable() {
private String stringData = null;
@Override
public void run() {
try {
ServerSocket ss = new ServerSocket(9002);
while (!end) {
//Server is waiting for client here, if needed
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream());
stringData = input.readLine();
output.println("FROM SERVER - " + stringData.toUpperCase());
output.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
updateUI(stringData);
if (stringData.equalsIgnoreCase("STOP")) {
end = true;
output.close();
s.close();
break;
}
output.close();
s.close();
}
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
private void updateUI(final String stringData) {
handler.post(new Runnable() {
@Override
public void run() {
String s = textViewDataFromClient.getText().toString();
if (stringData.trim().length() != 0)
textViewDataFromClient.setText(s + "\n" + "From Client : " + stringData);
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start_receiving:
startServerSocket();
buttonStartReceiving.setEnabled(false);
buttonStopReceiving.setEnabled(true);
break;
case R.id.btn_stop_receiving:
//stopping server socket logic you can add yourself
buttonStartReceiving.setEnabled(true);
buttonStopReceiving.setEnabled(false);
break;
}
}
}
plastic
, for my case.You can do it as below:
history.replaceState({}, document.title, window.location.href.split('#')[0]);
You did not specify the database engine in question; in Oracle, an option is to use tuples like this:
SELECT * FROM table WHERE (Col, 1) IN ((123,1),(123,1),(222,1),....)
This ugly hack only works in Oracle SQL, see https://asktom.oracle.com/pls/asktom/asktom.search?tag=limit-and-conversion-very-long-in-list-where-x-in#9538075800346844400
However, a much better option is to use stored procedures and pass the values as an array.
This code will do what you're looking for. It's based on examples found here and here.
The autofmt_xdate()
call is particularly useful for making the x-axis labels readable.
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)
fig.autofmt_xdate()
plt.savefig("figure.pdf")
A DataFrame
is defined well with a google search for "DataFrame definition":
A data frame is a table, or two-dimensional array-like structure, in which each column contains measurements on one variable, and each row contains one case.
So, a DataFrame
has additional metadata due to its tabular format, which allows Spark to run certain optimizations on the finalized query.
An RDD
, on the other hand, is merely a Resilient Distributed Dataset that is more of a blackbox of data that cannot be optimized as the operations that can be performed against it, are not as constrained.
However, you can go from a DataFrame to an RDD
via its rdd
method, and you can go from an RDD
to a DataFrame
(if the RDD is in a tabular format) via the toDF
method
In general it is recommended to use a DataFrame
where possible due to the built in query optimization.
I think you've actually got a wider confusion here.
The initial error is that you're trying to call split
on the whole list of lines, and you can't split
a list of strings, only a string. So, you need to split
each line, not the whole thing.
And then you're doing for points in Type
, and expecting each such points
to give you a new x
and y
. But that isn't going to happen. Types
is just two values, x
and y
, so first points
will be x
, and then points will be y
, and then you'll be done. So, again, you need to loop over each line and get the x
and y
values from each line, not loop over a single Types
from a single line.
So, everything has to go inside a loop over every line in the file, and do the split
into x
and y
once for each line. Like this:
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
for line in readfile:
Type = line.split(",")
x = Type[1]
y = Type[2]
print(x,y)
getQuakeData()
As a side note, you really should close
the file, ideally with a with
statement, but I'll get to that at the end.
Interestingly, the problem here isn't that you're being too much of a newbie, but that you're trying to solve the problem in the same abstract way an expert would, and just don't know the details yet. This is completely doable; you just have to be explicit about mapping the functionality, rather than just doing it implicitly. Something like this:
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
readlines = readfile.readlines()
Types = [line.split(",") for line in readlines]
xs = [Type[1] for Type in Types]
ys = [Type[2] for Type in Types]
for x, y in zip(xs, ys):
print(x,y)
getQuakeData()
Or, a better way to write that might be:
def getQuakeData():
filename = input("Please enter the quake file: ")
# Use with to make sure the file gets closed
with open(filename, "r") as readfile:
# no need for readlines; the file is already an iterable of lines
# also, using generator expressions means no extra copies
types = (line.split(",") for line in readfile)
# iterate tuples, instead of two separate iterables, so no need for zip
xys = ((type[1], type[2]) for type in types)
for x, y in xys:
print(x,y)
getQuakeData()
Finally, you may want to take a look at NumPy and Pandas, libraries which do give you a way to implicitly map functionality over a whole array or frame of data almost the same way you were trying to.
Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like
Nothing works and what mostly annoys me it's the fact that it works in the command line.
In addition to the above, you can do this (where "YourListObjectName" is the name of your table):
Dim LO As ListObject
Set LO = ActiveSheet.ListObjects("YourListObjectName")
But I think that only works if you want to reference a list object that's on the active sheet.
I found your question because I wanted to refer to a list object (a table) on one worksheet that a pivot table on a different worksheet refers to. Since list objects are part of the Worksheets collection, you have to know the name of the worksheet that list object is on in order to refer to it. So to get the name of the worksheet that the list object is on, I got the name of the pivot table's source list object (again, a table) and looped through the worksheets and their list objects until I found the worksheet that contained the list object I was looking for.
Public Sub GetListObjectWorksheet()
' Get the name of the worksheet that contains the data
' that is the pivot table's source data.
Dim WB As Workbook
Set WB = ActiveWorkbook
' Create a PivotTable object and set it to be
' the pivot table in the active cell:
Dim PT As PivotTable
Set PT = ActiveCell.PivotTable
Dim LO As ListObject
Dim LOWS As Worksheet
' Loop through the worksheets and each worksheet's list objects
' to find the name of the worksheet that contains the list object
' that the pivot table uses as its source data:
Dim WS As Worksheet
For Each WS In WB.Worksheets
' Loop through the ListObjects in each workshet:
For Each LO In WS.ListObjects
' If the ListObject's name is the name of the pivot table's soure data,
' set the LOWS to be the worksheet that contains the list object:
If LO.Name = PT.SourceData Then
Set LOWS = WB.Worksheets(LO.Parent.Name)
End If
Next LO
Next WS
Debug.Print LOWS.Name
End Sub
Maybe someone knows a more direct way.
On the MAC OS X 10.9.5 and Eclipse Luna Service Release 1 (4.4.1), its not found under the Window menu, but instead under: Eclipse > Preferences > Run/Debug > Console.
select one.*, two.meal
from table1 as one
left join table2 as two
on (one.weddingtable = two.weddingtable and one.tableseat = two.tableseat)
Answer https://stackoverflow.com/a/21369918/2526049 from dcodesmith has a side effect that turns all types of lists numeric.
<ol type="a">
will show 1. 2. 3. 4. rather than a. b. c. d.
ol {
margin: 0 0 1.5em;
padding: 0;
counter-reset: item;
}
ol > li {
margin: 0;
padding: 0 0 0 2em;
text-indent: -2em;
list-style-type: none;
counter-increment: item;
}
ol > li:before {
display: inline-block;
width: 1em;
padding-right: 0.5em;
font-weight: bold;
text-align: right;
content: counter(item) ".";
}
/* Add support for non-numeric lists */
ol[type="a"] > li:before {
content: counter(item, lower-alpha) ".";
}
ol[type="i"] > li:before {
content: counter(item, lower-roman) ".";
}
The above code adds support for lowercase letters, lowercase roman numerals. At the time of writing browsers do not differentiate between upper and lower case selectors for type so you can only pick uppercase or lowercase for your alternate ol types I guess.
I want to clear here that preg_split();
is far away from it but explode();
can be used in similar way as split();
following is the comparison between split();
and explode();
usage
<?php
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo $month; // foo
echo $day; // *
echo $year;
?>
URL: http://php.net/manual/en/function.split.php
<?php
$data = "04/30/1973";
list($month, $day, $year) = explode("/", $data);
echo $month; // foo
echo $day; // *
echo $year;
?>
URL: http://php.net/manual/en/function.explode.php
Here is how we can use it :)
try to disable the rewrite module in ubuntu using sudo a2dismod rewrite
. This will perhaps stop your apache server to crash.
Open tsconfig.json and disable strictDomEventTypes.
"angularCompilerOptions": {
....
........
"strictDomEventTypes": false
}
Nothing work for me but when i set tint color it works on Shape Drawable
Drawable background = imageView.getBackground();
background.setTint(getRandomColor())
require android 5.0 API 21
One option that'll work with any version of PHP is to do what's already been suggested, which is something like this:
$eventTime = '2010-04-28 17:25:43';
$age = time() - strtotime($eventTime);
That will give you the age in seconds. From there, you can display it however you wish.
One problem with this approach, however, is that it won't take into account time shifts causes by DST. If that's not a concern, then go for it. Otherwise, you'll probably want to use the diff() method in the DateTime class. Unfortunately, this is only an option if you're on at least PHP 5.3.
For me the problem got solved by simply reinstalling mysql-python
pip uninstall mysql-python
pip install mysql-python
Status 422 (RFC 4918, Section 11.2) comes to mind:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Write-Host -NoNewline "Enabling feature XYZ......."
There's an easier way to think about this. Start with 1 bit. This can obviously represent 2 values (0 or 1). What happens when we add a bit? We can now represent twice as many values: the values we could represent before with a 0 appended and the values we could represent before with a 1 appended.
So the the number of values we can represent with n bits is just 2^n (2 to the power n)
You could return an Integer
instead of an int
, returning null
on parse failure.
It's a shame Java doesn't provide a way of doing this without there being an exception thrown internally though - you can hide the exception (by catching it and returning null), but it could still be a performance issue if you're parsing hundreds of thousands of bits of user-provided data.
EDIT: Code for such a method:
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
Note that I'm not sure off the top of my head what this will do if text
is null. You should consider that - if it represents a bug (i.e. your code may well pass an invalid value, but should never pass null) then throwing an exception is appropriate; if it doesn't represent a bug then you should probably just return null as you would for any other invalid value.
Originally this answer used the new Integer(String)
constructor; it now uses Integer.parseInt
and a boxing operation; in this way small values will end up being boxed to cached Integer
objects, making it more efficient in those situations.
net stop <your service> && net start <your service>
No net restart
, unfortunately.
I would suggest using the duplicated method on the Pandas Index itself:
df3 = df3[~df3.index.duplicated(keep='first')]
While all the other methods work, the currently accepted answer is by far the least performant for the provided example. Furthermore, while the groupby method is only slightly less performant, I find the duplicated method to be more readable.
Using the sample data provided:
>>> %timeit df3.reset_index().drop_duplicates(subset='index', keep='first').set_index('index')
1000 loops, best of 3: 1.54 ms per loop
>>> %timeit df3.groupby(df3.index).first()
1000 loops, best of 3: 580 µs per loop
>>> %timeit df3[~df3.index.duplicated(keep='first')]
1000 loops, best of 3: 307 µs per loop
Note that you can keep the last element by changing the keep argument to 'last'
.
It should also be noted that this method works with MultiIndex
as well (using df1 as specified in Paul's example):
>>> %timeit df1.groupby(level=df1.index.names).last()
1000 loops, best of 3: 771 µs per loop
>>> %timeit df1[~df1.index.duplicated(keep='last')]
1000 loops, best of 3: 365 µs per loop
To just restore the KEY ALIAS. Type the below command on terminal.
$ keytool -list -v -keystore <storekey>
It will give information starting,
Your keystore contains 2 entries...
You can look for the alias name there.
Following will give you active connections/ queries in postgres DB-
SELECT
pid
,datname
,usename
,application_name
,client_hostname
,client_port
,backend_start
,query_start
,query
,state
FROM pg_stat_activity
WHERE state = 'active';
You may use 'idle' instead of active to get already executed connections/queries.
The destructor of A will run when its lifetime is over. If you want its memory to be freed and the destructor run, you have to delete it if it was allocated on the heap. If it was allocated on the stack this happens automatically (i.e. when it goes out of scope; see RAII). If it is a member of a class (not a pointer, but a full member), then this will happen when the containing object is destroyed.
class A
{
char *someHeapMemory;
public:
A() : someHeapMemory(new char[1000]) {}
~A() { delete[] someHeapMemory; }
};
class B
{
A* APtr;
public:
B() : APtr(new A()) {}
~B() { delete APtr; }
};
class C
{
A Amember;
public:
C() : Amember() {}
~C() {} // A is freed / destructed automatically.
};
int main()
{
B* BPtr = new B();
delete BPtr; // Calls ~B() which calls ~A()
C *CPtr = new C();
delete CPtr;
B b;
C c;
} // b and c are freed/destructed automatically
In the above example, every delete and delete[] is needed. And no delete is needed (or indeed able to be used) where I did not use it.
auto_ptr
, unique_ptr
and shared_ptr
etc... are great for making this lifetime management much easier:
class A
{
shared_array<char> someHeapMemory;
public:
A() : someHeapMemory(new char[1000]) {}
~A() { } // someHeapMemory is delete[]d automatically
};
class B
{
shared_ptr<A> APtr;
public:
B() : APtr(new A()) {}
~B() { } // APtr is deleted automatically
};
int main()
{
shared_ptr<B> BPtr = new B();
} // BPtr is deleted automatically
It is called 'favicon' and you need to add below code to the header section of your website.
Simply add this to the <head>
section.
<link rel="icon" href="/your_path_to_image/favicon.jpg">
If your project generally relies on exceptions to distinguish bad data from good data, then throwing an exception from the constructor is better solution than not throwing. If exception is not thrown, then object is initialized in a zombie state. Such object needs to expose a flag which says whether the object is correct or not. Something like this:
class Scaler
{
public:
Scaler(double factor)
{
if (factor == 0)
{
_state = 0;
}
else
{
_state = 1;
_factor = factor;
}
}
double ScaleMe(double value)
{
if (!_state)
throw "Invalid object state.";
return value / _factor;
}
int IsValid()
{
return _status;
}
private:
double _factor;
int _state;
}
Problem with this approach is on the caller side. Every user of the class would have to do an if before actually using the object. This is a call for bugs - there's nothing simpler than forgetting to test a condition before continuing.
In case of throwing an exception from the constructor, entity which constructs the object is supposed to take care of problems immediately. Object consumers down the stream are free to assume that object is 100% operational from the mere fact that they obtained it.
This discussion can continue in many directions.
For example, using exceptions as a matter of validation is a bad practice. One way to do it is a Try pattern in conjunction with factory class. If you're already using factories, then write two methods:
class ScalerFactory
{
public:
Scaler CreateScaler(double factor) { ... }
int TryCreateScaler(double factor, Scaler **scaler) { ... };
}
With this solution you can obtain the status flag in-place, as a return value of the factory method, without ever entering the constructor with bad data.
Second thing is if you are covering the code with automated tests. In that case every piece of code which uses object which does not throw exceptions would have to be covered with one additional test - whether it acts correctly when IsValid() method returns false. This explains quite well that initializing objects in zombie state is a bad idea.
empty
is an operator:
The
empty
operator is a prefix operation that can be used to determine whether a value is null or empty.
<c:if test="${empty myObject.featuresList}">
Life is too short to spend it on messing with paths, etc.
Since I had Homebrew installed on the iMac, I just ran this command:
brew install gradle
The Ionic3 project started to build successfully.
This is a simple way of doing it:
result = mylist and all(mylist[0] == elem for elem in mylist)
This is slightly more complicated, it incurs function call overhead, but the semantics are more clearly spelled out:
def all_identical(seq):
if not seq:
# empty list is False.
return False
first = seq[0]
return all(first == elem for elem in seq)
Is it because some culture format issue?
Yes. Your user must be in a culture where the time separator is a dot. Both ":" and "/" are interpreted in a culture-sensitive way in custom date and time formats.
How can I make sure the result string is delimited by colon instead of dot?
I'd suggest specifying CultureInfo.InvariantCulture
:
string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",
CultureInfo.InvariantCulture);
Alternatively, you could just quote the time and date separators:
string text = dateTime.ToString("MM'/'dd'/'yyyy HH':'mm':'ss.fff");
... but that will give you "interesting" results that you probably don't expect if you get users running in a culture where the default calendar system isn't the Gregorian calendar. For example, take the following code:
using System;
using System.Globalization;
using System.Threading;
class Test
{
static void Main()
{
DateTime now = DateTime.Now;
CultureInfo culture = new CultureInfo("ar-SA"); // Saudi Arabia
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
}
}
That produces output (on September 18th 2013) of:
11/12/1434 15:04:31.750
My guess is that your web service would be surprised by that!
I'd actually suggest not only using the invariant culture, but also changing to an ISO-8601 date format:
string text = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff");
This is a more globally-accepted format - it's also sortable, and makes the month and day order obvious. (Whereas 06/07/2013 could be interpreted as June 7th or July 6th depending on the reader's culture.)
If you are using ES6 features and you're in an async function, you can effectively halt the code execution for a certain time with this function:
const delay = millis => new Promise((resolve, reject) => {
setTimeout(_ => resolve(), millis)
});
This is how you use it:
await delay(5000);
It will stall for the requested amount of milliseconds, but only if you're in an async function. Example below:
const myFunction = async function() {
// first code block ...
await delay(5000);
// some more code, executed 5 seconds after the first code block finishes
}
Here we can some something like this. And instead of using any shortcut we can write "default" comments at class/ package /project level. And modify as per requirement
*** Install JavaDoc Plugin ***
1.Press shift twice and Go to Plugins.
2. search for JavaDocs plugin
3. Install it.
4. Restart Android Studio.
5. Now, rightclick on Java file/package and goto
JavaDocs >> create javadocs for all elements
It will generate all default comments.
Advantage is that, you can create comment block for all the methods at a time.
To expand on Johan's answer, if the part_num column in the sub-select can contain null values then the query will break.
To correct this, add a null check...
SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN
(SELECT pd.part_num FROM wpsapi4.product_details pd
where pd.part_num is not null)
One question is if you also want to use git for the deploment of your projects. If so you probably would like to exclude your local sqlite file from the repository, same probably applies to file uploads (mostly in your media folder). (I'm talking about django now, since your question is also tagged with django)
Both certificates should exist prior to the connection. They're usually created by Certification Authorities (not necessarily the same). (There are alternative cases where verification can be done differently, but some verification will need to be made.)
The server certificate should be created by a CA that the client trusts (and following the naming conventions defined in RFC 6125).
The client certificate should be created by a CA that the server trusts.
It's up to each party to choose what it trusts.
There are online CA tools that will allow you to apply for a certificate within your browser and get it installed there once the CA has issued it. They need not be on the server that requests client-certificate authentication.
The certificate distribution and trust management is the role of the Public Key Infrastructure (PKI), implemented via the CAs. The SSL/TLS client and servers and then merely users of that PKI.
When the client connects to a server that requests client-certificate authentication, the server sends a list of CAs it's willing to accept as part of the client-certificate request. The client is then able to send its client certificate, if it wishes to and a suitable one is available.
The main advantages of client-certificate authentication are:
You may be interested in Advantages of client certificates for client authentication? (on Security.SE).
When modal hide? we check like this :
$('.yourmodal').on('hidden.bs.modal', function () {
// do something here
})
Here is the one through AWK:
$ foo="Hello"
$ foo=$(awk -v var=$foo 'BEGIN{print var" World"}')
$ echo $foo
Hello World
I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and @Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)
I pulled this from the example code in your link:
IF !%1==! GOTO VIEWDATA
REM IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM PRINT LINE WITH STRING MATCH, THEN EXIT.
:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM SHOW ENTIRE FILE, 1 PAGE AT A TIME.
:EXIT0
!%1==!
is simply an idiomatic use of ==
intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The !
in this case is just a character placeholder. It could be anything. If %1
has content, then the equality will be false, if it does not you'll just be comparing !
to !
and it will be true.
!==!
is not an operator, so writing "asdf" !==! "fdas"
is pretty nonsensical.
The suggestion to use if not "asdf" == "fdas"
is definitely the way to go.
I suspect you've got the same problem at least twice.
Here:
namespace TimeTest
{
class TimeTest
{
}
... you're declaring a type with the same name as the namespace it's in. Don't do that.
Now you apparently have the same problem with Time2
. I suspect if you add:
using Time2;
to your list of using
directives, your code will compile. But please, please, please fix the bigger problem: the problematic choice of names. (Follow the link above to find out more details of why it's a bad idea.)
(Additionally, unless you're really interested in writing time-based types, I'd advise you not to do so... and I say that as someone who does do exactly that. Use the built-in capabilities, or a third party library such as, um, mine. Working with dates and times correctly is surprisingly hairy. :)
byte[] conv = new byte[4];
conv[3] = (byte) input & 0xff;
input >>= 8;
conv[2] = (byte) input & 0xff;
input >>= 8;
conv[1] = (byte) input & 0xff;
input >>= 8;
conv[0] = (byte) input;
We can use following one liner in Java 8:
List<String> list = set.stream().collect(Collectors.toList());
Here is one small example:
public static void main(String[] args) {
Set<String> set = new TreeSet<>();
set.add("A");
set.add("B");
set.add("C");
List<String> list = set.stream().collect(Collectors.toList());
}
Go to Project location in Specified Folder
C:\Angular6\sample>
Here you can type the command
C:\Angular6\sample>ng g c users
Here g means generate , c means component ,users is the component name
it will generate the 4 files
users.component.html,
users.component.spec.ts,
users.component.ts,
users.component.css
AWK printf-based solution that avoids % problem, and is unique in that it returns nothing (no return character) if there are less than 4 columns to print:
awk 'NF > 3 { for(i=4; i<NF; i++) printf("%s ", $(i)); print $(i) }'
Testing:
$ x='1 2 3 %s 4 5 6'
$ echo "$x" | awk 'NF > 3 { for(i=4; i<NF; i++) printf("%s ", $(i)); print $(i) }'
%s 4 5 6
$ x='1 2 3'
$ echo "$x" | awk 'NF > 3 { for(i=4; i<NF; i++) printf("%s ", $(i)); print $(i) }'
$ x='1 2 3 '
$ echo "$x" | awk 'NF > 3 { for(i=4; i<NF; i++) printf("%s ", $(i)); print $(i) }'
$
I don't know if this solves your problem but instead of:
$("#tbIntervalos").find("td").attr("id", horaInicial);
you can just do:
$("#tbIntervalos td#" + horaInicial);
Using setInterval:
setInterval(function() {
// your code goes here...
}, 60 * 1000); // 60 * 1000 milsec
The function returns an id you can clear your interval with clearInterval:
var timerID = setInterval(function() {
// your code goes here...
}, 60 * 1000);
clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.
A "sister" function is setTimeout/clearTimeout look them up.
If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:
function fn60sec() {
// runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
Nobody has mention this in. above answers so i am mentioning it.
This error can also come if you're in the wrong folder or path of your pem file is not correct. I was having similar issue and found that my pem file was not there from where i am executing the ssh command
cd KeyPair
ssh -i Keypair.pem [email protected]
As mentioned before, look at the -S flag.
It's also worth looking at the '-fdump-tree' family of flags, in particular '-fdump-tree-all', which lets you see some of gcc's intermediate forms. These can often be more readable than assembler (at least to me), and let you see how optimisation passes perform.
I am able to download it using apple's download website today. https://developer.apple.com/download/
I do not have a paid apple developer account. Before I was only able to see xcode 8.3.3 but somehow today xcode 9 beta also appeared.
With iOS 13, as stated in the Platforms State of the Union during the WWDC 2019, Apple introduced a new default card presentation. In order to force the fullscreen you have to specify it explicitly with:
let vc = UIViewController()
vc.modalPresentationStyle = .fullScreen //or .overFullScreen for transparency
self.present(vc, animated: true, completion: nil)
I was able to workaround/hack this problem by moving in to "Classic" mode from "integrated" mode.
Had the same problem. But only on my own methods.
Just fixed it by invalidating cache: (File-> Invalidate Caches/Restart)
I believe SET
is ANSI standard whereas the SELECT
is not. Also note the different behavior of SET
vs. SELECT
in the example below when a value is not found.
declare @var varchar(20)
set @var = 'Joe'
set @var = (select name from master.sys.tables where name = 'qwerty')
select @var /* @var is now NULL */
set @var = 'Joe'
select @var = name from master.sys.tables where name = 'qwerty'
select @var /* @var is still equal to 'Joe' */
You can find a customizer on the official website, which allows you to set some LESS variables, as @font-family-base
. Link your custom fonts in your layout, and use your custom generated bootstrap style.
For an example with the @font-face
rule, using WOFF format (which is pretty good for browser compatibility), add this CSS in your app.css
file and include your custom boostrap.css
file.
@font-face {
font-family: 'Proxima Nova';
font-style: normal;
font-weight: 400;
src: url(link-to-proxima-nova-font.woff) format('woff');
}
There's a fantastic ORM included in the QCubed framework; it's based on code generation and scaffolding. Unlike the ActiveRecord that's based on reflection and is generally slow, code generation makes skeleton classes for you based on the database and lets you customize them afterward. It works like a charm.
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
Not really, no.
You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class).
You might also find this article interesting / useful : A Java Programmer Looks at C# Delegates (@blueskyprojects.com)
It was used for "intermediate materialization (Google search)"
Good article: Adam Machanic: Exploring the secrets of intermediate materialization
He even raised an MS Connect so it can be done in a cleaner fashion
My view is "not inherently bad", but don't use it unless 100% sure. The problem is, it works only at the time you do it and probably not later (patch level, schema, index, row counts etc)...
This may fail because you don't know in which order things are evaluated
SELECT foo From MyTable WHERE ISNUMERIC (foo) = 1 AND CAST(foo AS int) > 100
And this may also fail because
SELECT foo
FROM
(SELECT foo From MyTable WHERE ISNUMERIC (foo) = 1) bar
WHERE
CAST(foo AS int) > 100
However, this did not in SQL Server 2000. The inner query is evaluated and spooled:
SELECT foo
FROM
(SELECT TOP 100 PERCENT foo From MyTable WHERE ISNUMERIC (foo) = 1 ORDER BY foo) bar
WHERE
CAST(foo AS int) > 100
Note, this still works in SQL Server 2005
SELECT TOP 2000000000 ... ORDER BY...
at
is the correct way.
If you don't have the at
command in the machine and you also don't have install privilegies on it, you can put something like this on cron
(maybe with the crontab
command):
* * * 5 * /path/to/comand_to_execute; /usr/bin/crontab -l | /usr/bin/grep -iv command_to_execute | /usr/bin/crontab -
it will execute your command one time and remove it from cron
after that.
Below is the work around to submit Multi values, in case of converting the application from ASP to PHP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script language="javascript">
function SetValuesOfSameElements() {
var Arr_Elements = [];
Arr_Elements = document.getElementsByClassName("MultiElements");
for(var i=0; i<Arr_Elements.length; i++) {
Arr_Elements[i].value = '';
var Element_Name = Arr_Elements[i].name;
var Main_Element_Type = Arr_Elements[i].getAttribute("MainElementType");
var Multi_Elements = [];
Multi_Elements = document.getElementsByName(Element_Name);
var Multi_Elements_Values = '';
//alert(Element_Name + " > " + Main_Element_Type + " > " + Multi_Elements_Values);
if (Main_Element_Type == "CheckBox") {
for(var j=0; j<Multi_Elements.length; j++) {
if (Multi_Elements[j].checked == true) {
if (Multi_Elements_Values == '') {
Multi_Elements_Values = Multi_Elements[j].value;
}
else {
Multi_Elements_Values += ', '+ Multi_Elements[j].value;
}
}
}
}
if (Main_Element_Type == "Hidden" || Main_Element_Type == "TextBox") {
for(var j=0; j<Multi_Elements.length; j++) {
if (Multi_Elements_Values == '') {
Multi_Elements_Values = Multi_Elements[j].value;
}
else {
if (Multi_Elements[j].value != '') {
Multi_Elements_Values += ', '+ Multi_Elements[j].value;
}
}
}
}
Arr_Elements[i].value = Multi_Elements_Values;
}
}
</script>
<BODY>
<form name="Training" action="TestCB.php" method="get" onsubmit="SetValuesOfSameElements()"/>
<table>
<tr>
<td>Check Box</td>
<td>
<input type="CheckBox" name="TestCB" id="TestCB" value="123">123</input>
<input type="CheckBox" name="TestCB" id="TestCB" value="234">234</input>
<input type="CheckBox" name="TestCB" id="TestCB" value="345">345</input>
</td>
<td>
<input type="hidden" name="SdPart" id="SdPart" value="1231"></input>
<input type="hidden" name="SdPart" id="SdPart" value="2341"></input>
<input type="hidden" name="SdPart" id="SdPart" value="3451"></input>
<input type="textbox" name="Test11" id="Test11" value="345111"></input>
<!-- Define hidden Elements with Class name 'MultiElements' for all the Form Elements that used the Same Name (Check Boxes, Multi Select, Text Elements with the Same Name, Hidden Elements with the Same Name, etc
-->
<input type="hidden" MainElementType="CheckBox" name="TestCB" class="MultiElements" value=""></input>
<input type="hidden" MainElementType="Hidden" name="SdPart" class="MultiElements" value=""></input>
<input type="hidden" MainElementType="TextBox" name="Test11" class="MultiElements" value=""></input>
</td>
</tr>
<tr>
<td colspan="2">
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</td>
</tr>
</table>
</form>
</BODY>
</HTML>
testCB.php
<?php
echo $_GET["TestCB"];
echo "<br/>";
echo $_GET["SdPart"];
echo "<br/>";
echo $_GET["Test11"];
?>
You could make it into a module and expose your inner function by returning it in an Object.
function outer() {
function inner() {
console.log("hi");
}
return {
inner: inner
};
}
var foo = outer();
foo.inner();
You shouldn't use float unless you have to. In 99% of cases, double is a better choice.
int x = 1111111111;
int y = 10000;
float f = (float) x / y;
double d = (double) x / y;
System.out.println("f= "+f);
System.out.println("d= "+d);
prints
f= 111111.12
d= 111111.1111
Following @Matt's comment.
float has very little precision (6-7 digits) and shows significant rounding error fairly easily. double has another 9 digits of accuracy. The cost of using double instead of float is notional in 99% of cases however the cost of a subtle bug due to rounding error is much higher. For this reason, many developers recommend not using floating point at all and strongly recommend BigDecimal.
However I find that double can be used in most cases provided sensible rounding is used.
In this case, int x has 32-bit precision whereas float has a 24-bit precision, even dividing by 1 could have a rounding error. double on the other hand has 53-bit of precision which is more than enough to get a reasonably accurate result.
I'm using intelliJ 15 community edition and I'm able to right click a file and select 'add to .gitignore'
jQuery API specifically says not to bind to beforeunload, and instead should bind directly to the window.onbeforeunload, I just ran across a pretty bad memory in part due binding to beforeunload with jQuery.
I believe python arrays just admit values. So convert it to list:
kOUT = np.zeros(N+1)
kOUT = kOUT.tolist()
I found it useful to use a general expression. This way you can do stuff like automatically move focus when input text is valid
<button type="button" moo-focus-expression="form.phone.$valid">
Or automatically focus when the user completes a fixed length field
<button type="submit" moo-focus-expression="smsconfirm.length == 6">
And of course focus after load
<input type="text" moo-focus-expression="true">
The code for the directive:
.directive('mooFocusExpression', function ($timeout) {
return {
restrict: 'A',
link: {
post: function postLink(scope, element, attrs) {
scope.$watch(attrs.mooFocusExpression, function (value) {
if (attrs.mooFocusExpression) {
if (scope.$eval(attrs.mooFocusExpression)) {
$timeout(function () {
element[0].focus();
}, 100); //need some delay to work with ng-disabled
}
}
});
}
}
};
});
Two options:
Use the LIKE
keyword, along with percent signs in the string
select * from table where field like '%a%' or field like '%b%'.
(note: If your search string contains percent signs, you'll need to escape them)
If you're looking for more a complex combination of strings than you've specified in your example, you could regular expressions (regex):
See the MySQL manual for more on how to use them: http://dev.mysql.com/doc/refman/5.1/en/regexp.html
Of these, using LIKE
is the most usual solution -- it's standard SQL, and in common use. Regex is less commonly used but much more powerful.
Note that whichever option you go with, you need to be aware of possible performance implications. Searching for sub-strings like this will mean that the query will have to scan the entire table. If you have a large table, this could make for a very slow query, and no amount of indexing is going to help.
If this is an issue for you, and you'r going to need to search for the same things over and over, you may prefer to do something like adding a flag field to the table which specifies that the string field contains the relevant sub-strings. If you keep this flag field up-to-date when you insert of update a record, you could simply query the flag when you want to search. This can be indexed, and would make your query much much quicker. Whether it's worth the effort to do that is up to you, it'll depend on how bad the performance is using LIKE
.
NULL
isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef>
or #include <stddef.h>
should be sufficient.
The definition of NULL
is guaranteed to be available if you include cstddef
or stddef.h
. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.
Using Moshi:
When building your Retrofit Service add .asLenient() to your MoshiConverterFactory. You don't need a ScalarsConverter. It should look something like this:
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(ENDPOINT)
.addConverterFactory(MoshiConverterFactory.create().asLenient())
.build()
.create(UserService::class.java)
Yes, you can use Application.OnTime
for this and then put it in a loop. It's sort of like an alarm clock where you keep hittig the snooze button for when you want it to ring again. The following updates Cell A1 every three seconds with the time.
Dim TimerActive As Boolean
Sub StartTimer()
Start_Timer
End Sub
Private Sub Start_Timer()
TimerActive = True
Application.OnTime Now() + TimeValue("00:00:03"), "Timer"
End Sub
Private Sub Stop_Timer()
TimerActive = False
End Sub
Private Sub Timer()
If TimerActive Then
ActiveSheet.Cells(1, 1).Value = Time
Application.OnTime Now() + TimeValue("00:00:03"), "Timer"
End If
End Sub
You can put the StartTimer
procedure in your Auto_Open
event and change what is done in the Timer
proceedure (right now it is just updating the time in A1 with ActiveSheet.Cells(1, 1).Value = Time
).
Note: you'll want the code (besides StartTimer
) in a module, not a worksheet module. If you have it in a worksheet module, the code requires slight modification.
You should keep the select
element disabled
but also add another hidden input
with the same name and value.
If you reenable your SELECT, you should copy its value to the hidden input in an onchange event and disable (or remove) the hidden input.
Here is a demo:
$('#mainform').submit(function() {_x000D_
$('#formdata_container').show();_x000D_
$('#formdata').html($(this).serialize());_x000D_
return false;_x000D_
});_x000D_
_x000D_
$('#enableselect').click(function() {_x000D_
$('#mainform input[name=animal]')_x000D_
.attr("disabled", true);_x000D_
_x000D_
$('#animal-select')_x000D_
.attr('disabled', false)_x000D_
.attr('name', 'animal');_x000D_
_x000D_
$('#enableselect').hide();_x000D_
return false;_x000D_
});
_x000D_
#formdata_container {_x000D_
padding: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<form id="mainform">_x000D_
<select id="animal-select" disabled="true">_x000D_
<option value="cat" selected>Cat</option>_x000D_
<option value="dog">Dog</option>_x000D_
<option value="hamster">Hamster</option>_x000D_
</select>_x000D_
<input type="hidden" name="animal" value="cat"/>_x000D_
<button id="enableselect">Enable</button>_x000D_
_x000D_
<select name="color">_x000D_
<option value="blue" selected>Blue</option>_x000D_
<option value="green">Green</option>_x000D_
<option value="red">Red</option>_x000D_
</select>_x000D_
_x000D_
<input type="submit"/>_x000D_
</form>_x000D_
</div>_x000D_
_x000D_
<div id="formdata_container" style="display:none">_x000D_
<div>Submitted data:</div>_x000D_
<div id="formdata">_x000D_
</div>_x000D_
</div>
_x000D_
I got this to finally work in a semi-automatic fashion without the use of scripts... but it does take up 3 cells to pull it off. Borrowing from a bit from previous answers, I start with a cell that has nothing more than =NOW() it in to show the time. For example, we'll put this into cell A1...
=NOW()
This function updates automatically every minute. In the next cell, put a pointer formula using the sheets own name to point to the previous cell. For example, we'll put this in A2...
='Sheet Name'!A1
Cell formatting aside, cell A1 and A2 should at this point display the same content... namely the current time.
And, the last cell is the part I'm borrowing from previous solutions using a regex expression to pull the fomula from the second cell and then strip out the name of the sheet from said formula. For example, we'll put this into cell A3...
=REGEXREPLACE(FORMULATEXT(A2),"='?([^']+)'?!.*","$1")
At this point, the resultant value displayed in A3 should be the name of the sheet.
From my experience, as soon as the name of the sheet is changed, the formula in A2 is immediately updated. However that's not enough to trigger A3 to update. But, every minute when cell A1 recalculates the time, the result of the formula in cell A2 is subsequently updated and then that in turn triggers A3 to update with the new sheet name. It's not a compact solution... but it does seem to work.
try to set the transparency with the android-studio designer in activity_main.xml. If you want it to be transparent, write it for example like this for white: White: #FFFFFF, with 50% transparency: #80FFFFFF This is for Kotlin tho, not sure if that will work the same way for basic android (java).
I had the same problem while debugging a class library from a testbed web app. I was referencing the release version in the testbed and that was set to be optimised in the class library properties.
Un-ticking the optimise code checkbox for the release version in the class library properties, just while I am writing it, has solved the issue.
you can simple use this following code
train_data['labels']= train_data[["LABEL1","LABEL1","LABEL2","LABEL3","LABEL4","LABEL5","LABEL6","LABEL7"]].values.tolist()
train_df = pd.DataFrame(train_data, columns=['text','labels'])
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
Most Markdown parsers don't support tables without headers. That means the separation line for headers is mandatory.
PHP Markdown Extra "second line contains a mandatory separator line between the headers and the content"
RDiscount Uses PHP Markdown Extra syntax.
simple_tables
and multiline_tables
extensions)If you're able to change the CSS of the HTML output you can however leverage the :empty
pseudo class to hide an empty header and make it look like there is no header at all.
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
Create a taxonomy field category (field name = post_category) and import it in your template as shown below:
<?php
$categ = get_field('post_category');
$args = array( 'posts_per_page' => 6,
'category_name' => $categ->slug );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
//your code here
<?php endforeach;
wp_reset_postdata();?>
Here's what worked for me: right click the project-> source -> format After that just drag and drop the source folder into eclipse under the project and select link.
good luck!
See ?nchar
. For example:
> nchar("foo")
[1] 3
> set.seed(10)
> strn <- paste(sample(LETTERS, 10), collapse = "")
> strn
[1] "NHKPBEFTLY"
> nchar(strn)
[1] 10
Based on the link provided by Philip I got this to working
Worksheets("Final Analysis Sheet").Range("A4:G112").CopyPicture xlScreen, xlBitmap
Application.DisplayAlerts = False
Set oCht = Charts.Add
With oCht
.Paste
.Export Filename:="C:\FTPDailycheck\TodaysImages\SavedRange.jpg", Filtername:="JPG"
.Delete
End With
While there are a lot of answers which focuses on solving the issue at hand but don't talk much about the various trade-off which someone needs to make before choosing a particular answer. So let me try to add a few more details on this perspective.
Partial search is now a day a very common and important feature and if not implemented properly can lead to poor user experience and bad performance, so first know your application function and non-function requirement related to this feature which I talked about in my this detailed SO answer.
Now there are various approaches, like query time, index time, completion suggester and search as you type data-types added in recent version of elasticsarch.
Now people who quickly want to just implement a solution can use below end to end working solution.
Index mapping
{
"settings": {
"analysis": {
"filter": {
"autocomplete_filter": {
"type": "ngram",
"min_gram": 1,
"max_gram": 10
}
},
"analyzer": {
"autocomplete": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"autocomplete_filter"
]
}
}
},
"index.max_ngram_diff" : 10
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
}
}
}
Index given sample docs
{
"title" : "John Doeman"
}
{
"title" : "Jane Doewoman"
}
{
"title" : "Jimmy Jackal"
}
And search query
{
"query": {
"match": {
"title": "Doe"
}
}
}
which returns expected search results
"hits": [
{
"_index": "6467067",
"_type": "_doc",
"_id": "1",
"_score": 0.76718915,
"_source": {
"title": "John Doeman"
}
},
{
"_index": "6467067",
"_type": "_doc",
"_id": "2",
"_score": 0.76718915,
"_source": {
"title": "Jane Doewoman"
}
}
]
The simplest command which can give you what you need but some other good info too is:
hostnamectl
I would use SWFUpload or Uploadify. They need Flash but do everything you want without troubles.
Any <input type="file">
based workaround that tries to trigger the "open file" dialog by means other than clicking on the actual control could be removed from browsers for security reasons at any time. (I think in the current versions of FF and IE, it is not possible any more to trigger that event programmatically.)
Here's my simple solution. That does not require any dependency.
However, the date will be in string format. If you want the time then change the substring values
print(new DateTime.now()
.toString()
.substring(0,10)
); // 2020-06-10
Try this, you will not force to inject $rootScope
in controller.
app.run(function($rootScope) {
$rootScope.Currency = 'USD';
});
You can only use it in run block because config block will not provide you to use service of $rootScope.
Try this to get value from select element by Element Name
$("select[name=elementnamehere]").val();
I got this error too, but my problem was that I was using an older version of GACUTIL.EXE
.
Once I had the correct GACUTIL
for the latest .NET
version installed, it worked fine.
The error is misleading because it makes it look like it's the DLL you're trying to register that incorrect.
A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.
A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.
(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).
The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:
You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.
In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.
This topic is very well covered in the documentation.
http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523
12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm
For cases where you also wish to have the option of setting 'b' to None:
def p(self, **kwargs):
b = kwargs.get('b', self.a)
print b
Like others have said, it's not possible with just JavaScript due to the security model of such.
If you are able to, I'd recommend one of the below solutions..both of which use a flash component for the client side validations; however, are wired up using Javascript/jQuery. Both work very well and can be used with any server-side tech.
This is another simple solution to generate random number of N digits:
$number_of_digits = 10;
echo substr(number_format(time() * mt_rand(),0,'',''),0,$number_of_digits);
Check it here: http://codepad.org/pyVvNiof
Since you explicitly asked for VB as well, let me just add that this verbatim string syntax doesn't exist in VB, only in C#. Rather, all strings are verbatim in VB (except for the fact that they cannot contain line breaks, unlike C# verbatim strings):
Dim path = "C:\My\Path"
Dim message = "She said, ""Hello, beautiful world."""
Escape sequences don't exist in VB (except for the doubling of the quote character, like in C# verbatim strings) which makes a few things more complicated. For example, to write the following code in VB you need to use concatenation (or any of the other ways to construct a string)
string x = "Foo\nbar";
In VB this would be written as follows:
Dim x = "Foo" & Environment.NewLine & "bar"
(&
is the VB string concatenation operator. +
could equally be used.)
returning true or false indicates that whether execution should continue or stop right there. So just an example
<input type="button" onclick="return func();" />
Now if func() is defined like this
function func()
{
// do something
return false;
}
the click event will never get executed. On the contrary if return true is written then the click event will always be executed.
Super easy.
Just divide the number of allocated bytes by the number of bytes of the array's data type using sizeof()
.
For example, given an integer array called myArray
int numArrElements = sizeof(myArray) / sizeof(int);
Now, if the data type of your array isn't constant and could possibly change, make the divisor in the equation use the size of the first value as the size of the data type
For example:
int numArrElements = sizeof(myArray) / sizeof(myArray[0]);
If you are using IntelliJ IDEA or Android Studio:
Go to Settings > Editor > General >Auto Import and check the Optimize imports on the fly checkbox.
You could use a simple regular expression to assert that the id only contains allowed characters, like so:
if(id.match(/^[0-9a-zA-Z]{1,16}$/)){
//The id is fine
}
else{
//The id is illegal
}
My example allows only alphanumerical characters, and strings of length 1 to 16, you should change it to match the type of ids that you use.
By the way, at line 6, the value property is missing a pair of quotes, an easy mistake to make when you quote on two levels.
I can't see your actual data flow, depending on context this check may not at all be needed, or it may not be enough. In order to make a proper security review we would need more information.
In general, about built in escape or sanitize functions, don't trust them blindly. You need to know exactly what they do, and you need to establish that that is actually what you need. If it is not what you need, the code your own, most of the time a simple whitelisting regex like the one I gave you works just fine.
Check this out as well: using xml path
and pivot
| ACCOUNT | 2000 | 2001 | 2002 |
--------------------------------
| Asset | 205 | 142 | 421 |
| Equity | 365 | 214 | 163 |
| Profit | 524 | 421 | 325 |
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period)
FROM demo c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT account, ' + @cols + ' from
(
select account
, value
, period
from demo
) x
pivot
(
max(value)
for period in (' + @cols + ')
) p '
execute(@query)
And as an addendum to all answers, FYI: override
is not a keyword, but a special kind of identifier! It has meaning only in the context of declaring/defining virtual functions, in other contexts it's just an ordinary identifier. For details read 2.11.2 of The Standard.
#include <iostream>
struct base
{
virtual void foo() = 0;
};
struct derived : base
{
virtual void foo() override
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
int main()
{
base* override = new derived();
override->foo();
return 0;
}
Output:
zaufi@gentop /work/tests $ g++ -std=c++11 -o override-test override-test.cc
zaufi@gentop /work/tests $ ./override-test
virtual void derived::foo()
Also, make sure you dont have a space after \ in previous line Else this is the error
Building on top of what Finesse wrote, here is a simpler way to target the svg and change it's gradient.
This is what you need to do:
Some benefits of using classes instead of :nth-child
is that it'll not be affected if you reorder your stops. Also, it makes the intent of each class clear - you'll be left wondering whether you needed a blue color on the first child or the second one.
I've tested it on all Chrome, Firefox and IE11:
.main-stop {_x000D_
stop-color: red;_x000D_
}_x000D_
.alt-stop {_x000D_
stop-color: green;_x000D_
}
_x000D_
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
<linearGradient id="gradient">_x000D_
<stop class="main-stop" offset="0%" />_x000D_
<stop class="alt-stop" offset="100%" />_x000D_
</linearGradient>_x000D_
<rect width="100" height="50" fill="url(#gradient)" />_x000D_
</svg>
_x000D_
See an editable example here: https://jsbin.com/gabuvisuhe/edit?html,css,output
var data = {
"items": [{
"id": 1,
"category": "cat1"
}, {
"id": 2,
"category": "cat2"
}, {
"id": 3,
"category": "cat1"
}]
};
var returnedData = $.grep(data.items, function (element, index) {
return element.id == 1;
});
alert(returnedData[0].id + " " + returnedData[0].category);
The returnedData is returning an array of objects, so you can access it by array index.
const Console = prop => (
console[Object.keys(prop)[0]](...Object.values(prop))
,null // ? React components must return something
)
// Some component with JSX and a logger inside
const App = () =>
<div>
<p>imagine this is some component</p>
<Console log='foo' />
<p>imagine another component</p>
<Console warn='bar' />
</div>
// Render
ReactDOM.render(
<App />,
document.getElementById("react")
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
Because this is HTML is not valid does not have any affect on the outcome ... it just means that the HTML does adhere to the standard (merely for organizational purposes). For the sake of being valid it could have been written this way:
<html>
<head>
<style type="text/css">
p.first {color:blue}
p.second {color:green}
</style>
</head>
<body>
<p class="first" style="color:green;">Hello World</p>
<p class="second" style="color:blue;">Hello World</p>
My guess is that the browser applies the last style it comes across.
Two possible solutions:
This answer uses bits of other answers, but hopefully it'll be a bit clearer as to the circumstances. You never specified what you were rsyncing - a single directory entry or multiple files.
So let's assume you are moving a source directory entry across, and not just moving the files contained in it.
Let's say you have a directory locally called data/myappdata/
and you have a load of subdirectories underneath this.
You have data/
on your target machine but no data/myappdata/
- this is easy enough:
rsync -rvv /path/to/data/myappdata/ user@host:/remote/path/to/data/myappdata
You can even use a different name for the remote directory:
rsync -rvv --recursive /path/to/data/myappdata user@host:/remote/path/to/data/newdirname
If you're just moving some files and not moving the directory entry that contains them then you would do:
rsync -rvv /path/to/data/myappdata/*.txt user@host:/remote/path/to/data/myappdata/
and it will create the myappdata
directory for you on the remote machine to place your files in. Again, the data/
directory must exist on the remote machine.
Incidentally, my use of -rvv
flag is to get doubly verbose output so it is clear about what it does, as well as the necessary recursive behaviour.
Just to show you what I get when using rsync (3.0.9 on Ubuntu 12.04)
$ rsync -rvv *.txt [email protected]:/tmp/newdir/
opening connection using: ssh -l user remote.machine rsync --server -vvre.iLsf . /tmp/newdir/
[email protected]'s password:
sending incremental file list
created directory /tmp/newdir
delta-transmission enabled
bar.txt
foo.txt
total: matches=0 hash_hits=0 false_alarms=0 data=0
Hope this clears this up a little bit.
Use the basename
method of the path
module:
path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'
Here is the documentation the above example is taken from.
And if you wanna work with data object, this two implements very important:
public class User implements Parcelable
check more in here
User3550138 is correct. lonefy.vscode-js-css-html-formatter
overrides all the settings mentioned in other answers. However, you don't have to disable or uninstall it as it can be configured.
Full instructions can be found by opening the extensions sidebar and clicking on this extension and it will display configuration instructions in the editor workspace. At least it does for me in Visual Studio Code version 1.14.1.
Had a quick snoop around for this one, but this looks like it should work. I haven't tested it yet though.
File f = new File("."); // current directory
File[] files = f.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
Use tableView: willDisplayHeaderView:
to customize the view when it is about to be displayed.
This gives you the advantage of being able to take the view that was already created for the header view and extend it, instead of having to recreate the whole header view yourself.
Here is an example that colors the header section based on a BOOL and adds a detail text element to the header.
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// view.tintColor = [UIColor colorWithWhite:0.825 alpha:1.0]; // gray
// view.tintColor = [UIColor colorWithRed:0.825 green:0.725 blue:0.725 alpha:1.0]; // reddish
// view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0]; // pink
// Conditionally tint the header view
BOOL isMyThingOnOrOff = [self isMyThingOnOrOff];
if (isMyThingOnOrOff) {
view.tintColor = [UIColor colorWithRed:0.725 green:0.925 blue:0.725 alpha:1.0];
} else {
view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0];
}
/* Add a detail text label (which has its own view to the section header… */
CGFloat xOrigin = 100; // arbitrary
CGFloat hInset = 20;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xOrigin + hInset, 5, tableView.frame.size.width - xOrigin - (hInset * 2), 22)];
label.textAlignment = NSTextAlignmentRight;
[label setFont:[UIFont fontWithName:@"Helvetica-Bold" size:14.0]
label.text = @"Hi. I'm the detail text";
[view addSubview:label];
}
following some of the answers here, deleting some simulators from my Xcode Menu > Window > Devices > Simulators did nothing to help my dying disk space:
however, cd ~/Library/Developer/Xcode/iOS\ DeviceSupport
and running du -sh *
I got all of these guys:
2.9G 10.0.1 (14A403)
1.3G 10.1.1 (14B100)
2.9G 10.3.2 (14F89)
1.3G 10.3.3 (14G60)
1.9G 11.0.1 (15A402)
1.9G 11.0.3 (15A432)
2.0G 11.1.2 (15B202)
2.0G 11.2 (15C114)
2.0G 11.2.1 (15C153)
2.0G 11.2.2 (15C202)
2.0G 11.2.6 (15D100)
2.0G 11.4 (15F79)
2.0G 11.4.1 (15G77)
2.3G 12.0 (16A366)
2.3G 12.0.1 (16A404)
2.3G 12.1 (16B92)
All together that's 33 GB!
A blood bath ensued
see more details here
function check (list){
var foundRepeatingValue = false;
var newList = [];
for(i=0;i<list.length;i++){
var thisValue = list[i];
if(i>0){
if(newList.indexOf(thisValue)>-1){
foundRepeatingValue = true;
console.log("getting repeated");
return true;
}
} newList.push(thisValue);
} return false;
}
var list1 = ["dse","dfg","dse"];
check(list1);
Output:
getting repeated
true
Authentication issue: I use TortoiseGit GUI tool, I need to tell tortoise the username and password so that it can access to work with Git/GitHub/Gitlab code base. To tell it, rt click inside any folder to get TortoiseGit menu. Here TortoseGit > Settings Window > Select Credentials in left nav tree Enter URL:Git url Helper: Select windows if your windows credentials are same as the ones for Git or 'manager' if they are different userName; Git User Name Save this settings ans try again. You will be prompted for password and then it worked.
Just create a new branch:
git checkout -b newBranch
And if you do git status
you'll see that the state of the code hasn't changed and you can commit it to the new branch.
def find_substring():
s = 'bobobnnnnbobmmmbosssbob'
cnt = 0
for i in range(len(s)):
if s[i:i+3] == 'bob':
cnt += 1
print 'bob found: ' + str(cnt)
return cnt
def main():
print(find_substring())
main()
My 2cents, in a single system user you can set the port also on /etc/ssh/ssh_config then rsync will use the port set here
I know this question is old, but I'm not satisfied with the answers provided.
LOOKUP, VLOOKUP and HLOOKUP has performance issues and should really never be used.
Array functions has a lot of overhead and can also have performance issues, so it should only be used as a last resort.
COUNT and COUNTA run into problems if the data is not contiguously non-blank, i.e. you have blank spaces and then data again in the range in question
INDIRECT is volatile so it should only be used as a last resort
OFFSET is volatile so it should only be used as a last resort
any references to the last row or column possible (the 65536th row in Excel 2003, for instance) is not robust and results in extra overhead
This is what I use
when the data type is mixed: =max(MATCH(1E+306,[RANGE],1),MATCH("*",[RANGE],-1))
when it's known that the data contains only numbers: =MATCH(1E+306,[RANGE],1)
when it's known that the data contains only text: =MATCH("*",[RANGE],-1)
MATCH has the lowest overhead and is non-volatile, so if you're working with lots of data this is the best to use.
I have python 2.7.13 and 3.6.2 both installed. Install Anaconda for python 3 first and then you can use conda syntax to get 2.7. My install used: conda create -n py27 python=2.7.13 anaconda
I did the CSS way with my install of Bootstrap 3.0.0, since I am not that familiar with LESS. Here is the code that I added to my custom css file (which I load after bootstrap.css) which allowed me to control so the menu was always working like an accordion
.
Note: I wrapped my whole navbar
inside a div with the class sidebar
to separate out the behavior I wanted so it did not affect other navbars on my site, like the main menu. Adjust along your needs, hope it is of help.
/* Sidebar Menu Fix */
.sidebar .navbar-nav {
margin: 7.5px -15px;
}
.sidebar .navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 20px;
}
.sidebar .navbar-collapse {
max-height: 500px;
}
.sidebar .navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
box-shadow: none;
}
.sidebar .dropdown-menu > li > a {
color: #777777;
}
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #333333;
background-color: transparent;
}
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #555555;
background-color: #e7e7e7;
}
.sidebar .navbar-nav {
float: none;
}
.sidebar .navbar-nav > li {
float: none;
}
Additional note: I also added a change to the toggle of the main menu navbar
(since the code above on my site is used for a "submenu" on the side.
I changed:
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
into:
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse-topmenu">
And then also adjusted:
<div class="navbar-collapse collapse navbar-collapse">
into:
<div class="navbar-collapse collapse navbar-collapse-topmenu">
If you will only have one navbar
I guess you will not need to worry about this, but it helped me in my case.
I faced this problem. I had "Archive for required library spring-boot-devtools cannot be read or is not a valid ZIP file" and the solution was like that:- 1- determine the dependencies names that have problems(for may case it is spring-boot-devtools). 2- close eclipse. 3- search in your .m2 file on these dependencies(by name). 4- delete these folders. 5- reopen eclipse and let maven rebuild your dependencies again.
You can optionally overload the = operator for the variable and can put the breakpoint inside the overloaded function on specific condition.
If using xib
s, a very easy implementation is to encapsulate all subviews inside a container view with resizing flags (which you'll already be using for 3.5" and 4" compatibility) so that the view hierarchy looks something like this
and then in viewDidLoad
, do something like this:
- (void)viewDidLoad
{
[super viewDidLoad];
// initializations
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) // only for iOS 7 and above
{
CGRect frame = containerView.frame;
frame.origin.y += 20;
frame.size.height -= 20;
containerView.frame = frame;
}
}
This way, the nibs need not be modified for iOS 7 compatibility. If you have a background, it can be kept outside containerView
and let it cover the whole screen.
If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^
. Then add all files and commit again.
Please follow the steps below to install sshpass
in mac.
curl -O -L https://fossies.org/linux/privat/sshpass-1.06.tar.gz && tar xvzf sshpass-1.06.tar.gz
cd sshpass-1.06
./configure
sudo make install