I would use the SplFileObject class...
$file = new SplFileObject("filename");
if (!$file->eof()) {
$file->seek($lineNumber);
$contents = $file->current(); // $contents would hold the data from line x
}
Look for "poi-3.17.jar"!!!
Problem solved and errors disappeared.
DialogFragment comes with the power of a dialog and a Fragment. Basically all the lifecycle events are managed very well with DialogFragment automatically, like change in screen configuration etc.
Why don't you just make it easy and simple. If I need to know the number of days between today and say, March 10th, 2015, I can just enter the simple formula.
Lets say the static date is March 10th, 2015, and is in cell O5.
The formula to determine the number of days between today and O5 would be, =O5-Today()
Nothing fancy or DATEDIF stuff. Obviously, the cell where you type this formula in must have a data type of 'number'. Just type your date in normally in the reference cell, in this case O5.
Ok, I found this post very interesting and I would like to share some of my knowledge on creating a query. Thanks for this Fluffeh. Others who may read this and may feel that I'm wrong are 101% free to edit and criticise my answer. (Honestly, I feel very thankful for correcting my mistake(s).)
I'll be posting some of the frequently asked questions in MySQL
tag.
Given this schema
CREATE TABLE MovieList
(
ID INT,
MovieName VARCHAR(25),
CONSTRAINT ml_pk PRIMARY KEY (ID),
CONSTRAINT ml_uq UNIQUE (MovieName)
);
INSERT INTO MovieList VALUES (1, 'American Pie');
INSERT INTO MovieList VALUES (2, 'The Notebook');
INSERT INTO MovieList VALUES (3, 'Discovery Channel: Africa');
INSERT INTO MovieList VALUES (4, 'Mr. Bean');
INSERT INTO MovieList VALUES (5, 'Expendables 2');
CREATE TABLE CategoryList
(
MovieID INT,
CategoryName VARCHAR(25),
CONSTRAINT cl_uq UNIQUE(MovieID, CategoryName),
CONSTRAINT cl_fk FOREIGN KEY (MovieID) REFERENCES MovieList(ID)
);
INSERT INTO CategoryList VALUES (1, 'Comedy');
INSERT INTO CategoryList VALUES (1, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Drama');
INSERT INTO CategoryList VALUES (3, 'Documentary');
INSERT INTO CategoryList VALUES (4, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Action');
QUESTION
Find all movies that belong to at least both Comedy
and Romance
categories.
Solution
This question can be very tricky sometimes. It may seem that a query like this will be the answer:-
SELECT DISTINCT a.MovieName
FROM MovieList a
INNER JOIN CategoryList b
ON a.ID = b.MovieID
WHERE b.CategoryName = 'Comedy' AND
b.CategoryName = 'Romance'
which is definitely very wrong because it produces no result. The explanation of this is that there is only one valid value of CategoryName
on each row. For instance, the first condition returns true, the second condition is always false. Thus, by using AND
operator, both condition should be true; otherwise, it will be false. Another query is like this,
SELECT DISTINCT a.MovieName
FROM MovieList a
INNER JOIN CategoryList b
ON a.ID = b.MovieID
WHERE b.CategoryName IN ('Comedy','Romance')
and the result is still incorrect because it matches to record that has at least one match on the categoryName
. The real solution would be by counting the number of record instances per movie. The number of instance should match to the total number of the values supplied in the condition.
SELECT a.MovieName
FROM MovieList a
INNER JOIN CategoryList b
ON a.ID = b.MovieID
WHERE b.CategoryName IN ('Comedy','Romance')
GROUP BY a.MovieName
HAVING COUNT(*) = 2
Given schema,
CREATE TABLE Software
(
ID INT,
SoftwareName VARCHAR(25),
Descriptions VARCHAR(150),
CONSTRAINT sw_pk PRIMARY KEY (ID),
CONSTRAINT sw_uq UNIQUE (SoftwareName)
);
INSERT INTO Software VALUES (1,'PaintMe','used for photo editing');
INSERT INTO Software VALUES (2,'World Map','contains map of different places of the world');
INSERT INTO Software VALUES (3,'Dictionary','contains description, synonym, antonym of the words');
CREATE TABLE VersionList
(
SoftwareID INT,
VersionNo INT,
DateReleased DATE,
CONSTRAINT sw_uq UNIQUE (SoftwareID, VersionNo),
CONSTRAINT sw_fk FOREIGN KEY (SOftwareID) REFERENCES Software(ID)
);
INSERT INTO VersionList VALUES (3, 2, '2009-12-01');
INSERT INTO VersionList VALUES (3, 1, '2009-11-01');
INSERT INTO VersionList VALUES (3, 3, '2010-01-01');
INSERT INTO VersionList VALUES (2, 2, '2010-12-01');
INSERT INTO VersionList VALUES (2, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 3, '2011-12-01');
INSERT INTO VersionList VALUES (1, 2, '2010-12-01');
INSERT INTO VersionList VALUES (1, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 4, '2012-12-01');
QUESTION
Find the latest version on each software. Display the following columns: SoftwareName
,Descriptions
,LatestVersion
(from VersionNo column),DateReleased
Solution
Some SQL developers mistakenly use MAX()
aggregate function. They tend to create like this,
SELECT a.SoftwareName, a.Descriptions,
MAX(b.VersionNo) AS LatestVersion, b.DateReleased
FROM Software a
INNER JOIN VersionList b
ON a.ID = b.SoftwareID
GROUP BY a.ID
ORDER BY a.ID
(most RDBMS generates a syntax error on this because of not specifying some of the non-aggregated columns on the group by
clause) the result produces the correct LatestVersion
on each software but obviously the DateReleased
are incorrect. MySQL
doesn't support Window Functions
and Common Table Expression
yet as some RDBMS do already. The workaround on this problem is to create a subquery
which gets the individual maximum versionNo
on each software and later on be joined on the other tables.
SELECT a.SoftwareName, a.Descriptions,
b.LatestVersion, c.DateReleased
FROM Software a
INNER JOIN
(
SELECT SoftwareID, MAX(VersionNO) LatestVersion
FROM VersionList
GROUP BY SoftwareID
) b ON a.ID = b.SoftwareID
INNER JOIN VersionList c
ON c.SoftwareID = b.SoftwareID AND
c.VersionNO = b.LatestVersion
GROUP BY a.ID
ORDER BY a.ID
So that was it. I'll be posting another soon as I recall any other FAQ on MySQL
tag. Thank you for reading this little article. I hope that you have atleast get even a little knowledge from this.
UPDATE 1
Given Schema
CREATE TABLE userList
(
ID INT,
NAME VARCHAR(20),
CONSTRAINT us_pk PRIMARY KEY (ID),
CONSTRAINT us_uq UNIQUE (NAME)
);
INSERT INTO userList VALUES (1, 'Fluffeh');
INSERT INTO userList VALUES (2, 'John Woo');
INSERT INTO userList VALUES (3, 'hims056');
CREATE TABLE CONVERSATION
(
ID INT,
FROM_ID INT,
TO_ID INT,
MESSAGE VARCHAR(250),
DeliveryDate DATE
);
INSERT INTO CONVERSATION VALUES (1, 1, 2, 'hi john', '2012-01-01');
INSERT INTO CONVERSATION VALUES (2, 2, 1, 'hello fluff', '2012-01-02');
INSERT INTO CONVERSATION VALUES (3, 1, 3, 'hey hims', '2012-01-03');
INSERT INTO CONVERSATION VALUES (4, 1, 3, 'please reply', '2012-01-04');
INSERT INTO CONVERSATION VALUES (5, 3, 1, 'how are you?', '2012-01-05');
INSERT INTO CONVERSATION VALUES (6, 3, 2, 'sample message!', '2012-01-05');
QUESTION
Find the latest conversation between two users.
Solution
SELECT b.Name SenderName,
c.Name RecipientName,
a.Message,
a.DeliveryDate
FROM Conversation a
INNER JOIN userList b
ON a.From_ID = b.ID
INNER JOIN userList c
ON a.To_ID = c.ID
WHERE (LEAST(a.FROM_ID, a.TO_ID), GREATEST(a.FROM_ID, a.TO_ID), DeliveryDate)
IN
(
SELECT LEAST(FROM_ID, TO_ID) minFROM,
GREATEST(FROM_ID, TO_ID) maxTo,
MAX(DeliveryDate) maxDate
FROM Conversation
GROUP BY minFROM, maxTo
)
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.For Node.js you can also use the "util" module. It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.
cat file.json | node -e "process.stdin.pipe(new require('stream').Writable({write: chunk => {console.log(require('util').inspect(JSON.parse(chunk), {depth: null, colors: true}))}}))"
This demo is returning correctly for me in Chrome 14, FF3 and FF5 (with Firebug):
var mytextvalue = document.getElementById("mytext").value;
console.log(mytextvalue == ''); // true
console.log(mytextvalue == null); // false
and changing the console.log
to alert
, I still get the desired output in IE6.
You can't get value when calling getJSON
, only after response.
var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
myjson = json;
});
Nevermind! I found it :)
get_queried_object()->term_id;
I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.
It can use for use to read for Zeor base index or 1 one base index.
${loop.count}` it will give 1 starting base index.
${loop.index} it will give 0 base index as normal Index of array
start from 0.
For Example :
<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
<source srcset="${currentImage}" media="(min-width: 1000px)"></source>
<source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
<img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>
For more Info please refer this link
To create a Twitter share link with a photo, you first need to tweet out the photo from your Twitter account. Once you've tweeted it out, you need to grab the pic.twitter.com link and place that inside your twitter share url.
note: You won't be able to see the pic.twitter.com url so what I do is use a separate account and hit the retweet button. A modal will pop up with the link inside.
You Twitter share link will look something like this:
<a href="https://twitter.com/home?status=This%20photo%20is%20awesome!%20Check%20it%20out:%20pic.twitter.com/9Ee63f7aVp">Share on Twitter</a>
From http://pyyaml.org/wiki/PyYAMLDocumentation:
add_path_resolver(tag, path, kind)
adds a path-based implicit tag resolver. A path is a list of keys that form a path to a node in the representation graph. Paths elements can be string values, integers, or None. The kind of a node can be str, list, dict, or None.
#!/usr/bin/env python
import yaml
class Person(yaml.YAMLObject):
yaml_tag = '!person'
def __init__(self, name):
self.name = name
yaml.add_path_resolver('!person', ['Person'], dict)
data = yaml.load("""
Person:
name: XYZ
""")
print data
# {'Person': <__main__.Person object at 0x7f2b251ceb10>}
print data['Person'].name
# XYZ
You can also contain "using namespace ..." inside a function for example:
void test(const std::string& s) {
using namespace std;
cout << s;
}
Well, in the worst case, you could use:
git branch | grep '3\.2' | xargs git branch -D
This solution doesn't require an import:
tuple(map(lambda x, y: x + y, tuple1, tuple2))
use DECIMAL()
or NUMERIC()
as they are fixed precision and scale numbers.
SELECT fullName,
CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info
ORDER BY _totalBal DESC
Culture can be changed for a specific cell in grid view.
<%# DateTime.ParseExact(Eval("contractdate", "{0}"), "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.CurrentCulture) %>
For more detail check the link.
typedef enum state {DEAD,ALIVE} State;
| | | | | |^ terminating semicolon, required!
| | | type specifier | | |
| | | | ^^^^^ declarator (simple name)
| | | |
| | ^^^^^^^^^^^^^^^^^^^^^^^
| |
^^^^^^^-- storage class specifier (in this case typedef)
The typedef
keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern
or static
is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.
After the above declaration, the State
identifier becomes an alias for the type enum state {DEAD,ALIVE}
. The declaration also provides that type itself. However that isn't typedef
doing it. Any declaration in which enum state {DEAD,ALIVE}
appears as a type specifier introduces that type into the scope:
enum state {DEAD, ALIVE} stateVariable;
If enum state
has previously been introduced the typedef
has to be written like this:
typedef enum state State;
otherwise the enum
is being redefined, which is an error.
Like other declarations (except function parameter declarations), the typedef
declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:
typedef unsigned long ulong, *ulongptr;
| | | | | 1 | | 2 |
| | | | | | ^^^^^^^^^--- "pointer to" declarator
| | | | ^^^^^^------------- simple declarator
| | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier
This typedef
introduces two type names ulong
and ulongptr
, based on the unsigned long
type given in the specifier-qualifier list. ulong
is just a straight alias for that type. ulongptr
is declared as a pointer to unsigned long
, thanks to the *
syntax, which in this role is a kind of type construction operator which deliberately mimics the unary *
for pointer dereferencing used in expressions. In other words ulongptr
is an alias for the "pointer to unsigned long
" type.
Alias means that ulongptr
is not a distinct type from unsigned long *
. This is valid code, requiring no diagnostic:
unsigned long *p = 0;
ulongptr q = p;
The variables q
and p
have exactly the same type.
The aliasing of typedef
isn't textual. For instance if user_id_t
is a typedef
name for the type int
, we may not simply do this:
unsigned user_id_t uid; // error! programmer hoped for "unsigned int uid".
This is an invalid type specifier list, combining unsigned
with a typedef name. The above can be done using the C preprocessor:
#define user_id_t int
unsigned user_id_t uid;
whereby user_id_t
is macro-expanded to the token int
prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.
Among the disadvantages that it doesn't work well for derived types:
#define silly_macro int *
silly_macro not, what, you, think;
This declaration doesn't declare what
, you
and think
as being of type "pointer to int" because the macro-expansion is:
int * not, what, you, think;
The type specifier is int
, and the declarators are *not
, what
, you
and think
. So not
has the expected pointer type, but the remaining identifiers do not.
And that's probably 99% of everything about typedef
and type aliasing in C.
The Builder pattern might be of use here. Today I had the same issue. where I needed Set mutating operations to return me a reference of the Set object, so I can pass it to super class constructor so that they too can continue adding to same set by in turn constructing a new StringSetBuilder off of the Set that the child class just built. The builder class I wrote looks like this (in my case it's a static inner class of an outer class, but it can be its own independent class as well):
public interface Builder<T> {
T build();
}
static class StringSetBuilder implements Builder<Set<String>> {
private final Set<String> set = new HashSet<>();
StringSetBuilder add(String pStr) {
set.add(pStr);
return this;
}
StringSetBuilder addAll(Set<String> pSet) {
set.addAll(pSet);
return this;
}
@Override
public Set<String> build() {
return set;
}
}
Notice the addAll()
and add()
methods, which are Set returning counterparts of Set.add()
and Set.addAll()
. Finally notice the build()
method, which returns a reference to the Set that the builder encapsulates. Below illustrates then how to use this Set builder:
class SomeChildClass extends ParentClass {
public SomeChildClass(String pStr) {
super(new StringSetBuilder().add(pStr).build());
}
}
class ParentClass {
public ParentClass(Set<String> pSet) {
super(new StringSetBuilder().addAll(pSet).add("my own str").build());
}
}
In addition to what eugene and stevenl posted, you might encounter problems with using both <>
and <STDIN>
in one script: <>
iterates through (=concatenating) all files given as command line arguments.
However, should a user ever forget to specify a file on the command line, it will read from STDIN, and your code will wait forever on input
You can add data-dismiss="modal" to your button attributes which call angularjs funtion.
Such as;
<button type="button" class="btn btn-default" data-dismiss="modal">Send Form</button>
XAML
<Popup Name="myPopup">
<TextBlock Name="myPopupText"
Background="LightBlue"
Foreground="Blue">
Popup Text
</TextBlock>
</Popup>
c#
Popup codePopup = new Popup();
TextBlock popupText = new TextBlock();
popupText.Text = "Popup Text";
popupText.Background = Brushes.LightBlue;
popupText.Foreground = Brushes.Blue;
codePopup.Child = popupText;
you can find more details about the Popup Control from MSDN documentation.
There are lots of applications and methods in the market to decompile the apk file into java class but if the app is compiled with ProGuard rule then you are in a big trouble because this rule will shrink all the dex files into a small character name and then you can not trace back the implementation. see https://developer.android.com/studio/build/shrink-code for mode clarification.
Happy Coding...
RecyclerView can have any number of viewholders you want but for better readability lets see how to create one with two ViewHolders.
It can be done in three simple steps
public int getItemViewType(int position)
onCreateViewHolder()
methodonBindViewHolder()
methodHere is a small code snippet
public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int LAYOUT_ONE= 0;
private static final int LAYOUT_TWO= 1;
@Override
public int getItemViewType(int position)
{
if(position==0)
return LAYOUT_ONE;
else
return LAYOUT_TWO;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =null;
RecyclerView.ViewHolder viewHolder = null;
if(viewType==LAYOUT_ONE)
{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
viewHolder = new ViewHolderOne(view);
}
else
{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
viewHolder= new ViewHolderTwo(view);
}
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder.getItemViewType()== LAYOUT_ONE)
{
// Typecast Viewholder
// Set Viewholder properties
// Add any click listener if any
}
else {
ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
vaultItemHolder.name.setText(displayText);
vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
.......
}
});
}
}
//**************** VIEW HOLDER 1 ******************//
public class ViewHolderOne extends RecyclerView.ViewHolder {
public TextView name;
public ViewHolderOne(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.displayName);
}
}
//**************** VIEW HOLDER 2 ******************//
public class ViewHolderTwo extends RecyclerView.ViewHolder{
public ViewHolderTwo(View itemView) {
super(itemView);
..... Do something
}
}
}
In my opinion,the starting point to create this kind of recyclerView is the knowledge of this method. Since this method is optional to override therefore it is not visible in RecylerView class by default which in turn makes many developers(including me) wonder where to begin. Once you know that this method exists, creating such RecyclerView would be a cakewalk.
Lets see one example to prove my point. If you want to show two layout at alternate positions do this
@Override
public int getItemViewType(int position)
{
if(position%2==0) // Even position
return LAYOUT_ONE;
else // Odd position
return LAYOUT_TWO;
}
Check out the project where I have implemented this
in JDK 8, jdbc odbc bridge is no longer used and thus removed fro the JDK. to use Microsoft Access database in JAVA, you need 5 extra JAR libraries.
1- hsqldb.jar
2- jackcess 2.0.4.jar
3- commons-lang-2.6.jar
4- commons-logging-1.1.1.jar
5- ucanaccess-2.0.8.jar
add these libraries to your java project and start with following lines.
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<Path to your database i.e. MS Access DB>");
Statement s = conn.createStatement();
path could be like E:/Project/JAVA/DBApp
and then your query to be executed. Like
ResultSet rs = s.executeQuery("SELECT * FROM Course");
while(rs.next())
System.out.println(rs.getString("Title") + " " + rs.getString("Code") + " " + rs.getString("Credits"));
certain imports to be used. try catch block must be used and some necessary things no to be forgotten.
Remember, no need of bridging drivers like jdbc odbc or any stuff.
If you are having trouble changing it to a percentage, then see this answer.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">
<android.support.constraint.Guideline
android:id="@+id/guideline8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>
<TextView
android:id="@+id/textView6"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintBottom_toTopOf="@+id/guideline8"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
func showAlertAction(title: String, message: String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
print("Action")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
THis is other method
You can also use setCenter
method with add new marker
check below code
$('#my_map').gmap3({
action: 'setCenter',
map:{
options:{
zoom: 10
}
},
marker:{
values:
[
{latLng:[position.coords.latitude, position.coords.longitude], data:"Netherlands !"}
]
}
});
The accepted answer is not always correct. If you configure binary logging on MySQL, you can rollback the database to any previous point you still have a snapshot and binlog for.
7.5 Point-in-Time (Incremental) Recovery Using the Binary Log is a good starting point for learning about this facility.
If you are using Xamarin you can add this
Activity[(WindowSoftInputMode = SoftInput.StateAlwaysHidden)]
thereafter you can add this line in OnCreate() method
youredittext.ShowSoftInputOnFocus = false;
If the targeted device does not support the above code, you can use the code below in EditText click event
InputMethodManager Imm = (InputMethodManager)this.GetSystemService(Context.InputMethodService);
Imm.HideSoftInputFromWindow(youredittext.WindowToken, HideSoftInputFlags.None);
Here's a short version:
$('#ddlCodes').change(function() {
$('#txtEntry2').text($(this).find(":selected").text());
});
karim79 made a good catch, judging by your element name txtEntry2
may be a textbox, if it's any kind of input, you'll need to use .val()
instead or .text()
like this:
$('#txtEntry2').val($(this).find(":selected").text());
For the "what's wrong?" part of the question: .text()
doesn't take a selector, it takes text you want it set to, or nothing to return the text already there. So you need to fetch the text you want, then put it in the .text(string)
method on the object you want to set, like I have above.
If you need to create a user_id
then it would be a reasonable assumption that you are referencing a user table. In which case the migration shall be:
rails generate migration AddUserRefToProducts user:references
This command will generate the following migration:
class AddUserRefToProducts < ActiveRecord::Migration
def change
add_reference :user, :product, index: true
end
end
After running rake db:migrate
both a user_id
column and an index will be added to the products
table.
In case you just need to add an index to an existing column, e.g. name
of a user
table, the following technique may be helpful:
rails generate migration AddIndexToUsers name:string:index
will generate the following migration:
class AddIndexToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string
add_index :users, :name
end
end
Delete add_column
line and run the migration.
In the case described you could have issued rails generate migration AddIndexIdToTable index_id:integer:index
command and then delete add_column
line from the generated migration. But I'd rather recommended to undo the initial migration and add reference instead:
rails generate migration RemoveUserIdFromProducts user_id:integer
rails generate migration AddUserRefToProducts user:references
There is now a Get-FileHash function which is very handy.
PS C:\> Get-FileHash C:\Users\Andris\Downloads\Contoso8_1_ENT.iso -Algorithm SHA384 | Format-List
Algorithm : SHA384
Hash : 20AB1C2EE19FC96A7C66E33917D191A24E3CE9DAC99DB7C786ACCE31E559144FEAFC695C58E508E2EBBC9D3C96F21FA3
Path : C:\Users\Andris\Downloads\Contoso8_1_ENT.iso
Just change SHA384
to MD5
.
The example is from the official documentation of PowerShell 5.1. The documentation has more examples.
You can also use this code to get LayoutInflater:
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
NSAttributedString *attributedText =[[[NSAttributedString alloc]
initWithString:joyMeComment.content
attributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:TextFont]}] autorelease];
CGRect paragraphRect =
[attributedText boundingRectWithSize:CGSizeMake(kWith, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];
contentSize = paragraphRect.size;
contentSize.size.height+=10;
label.frame=contentSize;
if label's frame not add 10 this method will never work! hope this can help you! goog luck.
More easy and without addition modules
Math.random().toString(26).slice(2)
Based on Thilak's answer I was able to come up with this solution...
Since my form fields only show validation messages if a field is invalid, and has been touched by the user I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step_x000D_
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {_x000D_
angular.forEach(error, function(field) {_x000D_
field.$setTouched();_x000D_
});_x000D_
});_x000D_
// Prevent user from going to next step if current step is invalid_x000D_
if (!vm.rfiForm.stepTwo.$valid) {_x000D_
isValid = false;_x000D_
}
_x000D_
<!-- form field -->_x000D_
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">_x000D_
_x000D_
<!-- field label -->_x000D_
<label class="control-label">Suffix</label>_x000D_
<!-- end field label -->_x000D_
<!-- field input -->_x000D_
<select name="Parent_Suffix__c" class="form-control"_x000D_
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"_x000D_
ng-model="rfi.contact.Parent_Suffix__c" />_x000D_
<!-- end field input -->_x000D_
<!-- field help -->_x000D_
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">_x000D_
<span ng-message="required">this field is required</span>_x000D_
</span> _x000D_
<!-- end field help -->_x000D_
</div>_x000D_
<!-- end form field -->
_x000D_
git log
+ git branch
will find it for you:
% git log --all -- somefile
commit 55d2069a092e07c56a6b4d321509ba7620664c63
Author: Dustin Sallings <[email protected]>
Date: Tue Dec 16 14:16:22 2008 -0800
added somefile
% git branch -a --contains 55d2069
otherbranch
Supports globbing, too:
% git log --all -- '**/my_file.png'
The single quotes are necessary (at least if using the Bash shell) so the shell passes the glob pattern to git unchanged, instead of expanding it (just like with Unix find
).
My problem was I'm using RVM and had the wrong Ruby version activated...
Hope this helps at least one person
Did you try using print_r
to print it in human-readable form?
Another solution is to use stat_count()
when dealing with discrete variables (and stat_bin()
with continuous ones).
ggplot(data = df, aes(x = x)) +
geom_bar(stat = "count") +
stat_count(geom = "text", colour = "white", size = 3.5,
aes(label = ..count..),position=position_stack(vjust=0.5))
I had the SAME issue today and it was driving me nuts!!! What I had done was upgrade to node 8.10 and upgrade my NPM to the latest I uninstalled angular CLI
npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
I then verified my Cache from NPM if it wasn't up to date I cleaned it and ran the install again
if npm version is < 5 then use npm cache clean --force
npm install -g @angular/cli@latest
and created a new project file and create a new angular project.
You need to write a selector which selects the correct <input>
first. Ideally you use the element's ID $('#element_id')
, failing that the ID of it's container $('#container_id input')
, or the element's class $('input.class_name')
.
Your element has none of these and no context, so it's hard to tell you how to select it.
Once you have figured out the proper selector, you'd use the attr method to access the element's attributes. To get the name, you'd use $(selector).attr('name')
which would return (in your example) 'xxxxx'
.
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
also had problems with rapidly growing overlay2
/var/lib/docker/overlay2
- is a folder where docker store writable layers for your container.
docker system prune -a
- may work only if container is stopped and removed.
in my i was able to figure out what consumes space by going into overlay2
and investigating.
that folder contains other hash named folders. each of those has several folders including diff
folder.
diff
folder - contains actual difference written by a container with exact folder structure as your container (at least it was in my case - ubuntu 18...)
so i've used du -hsc /var/lib/docker/overlay2/LONGHASHHHHHHH/diff/tmp
to figure out that /tmp
inside of my container is the folder which gets polluted.
so as a workaround i've used -v /tmp/container-data/tmp:/tmp
parameter for docker run
command to map inner /tmp
folder to host and setup a cron on host to cleanup that folder.
cron task was simple:
sudo nano /etc/crontab
*/30 * * * * root rm -rf /tmp/container-data/tmp/*
save and exit
NOTE: overlay2
is system docker folder, and they may change it structure anytime. Everything above is based on what i saw in there. Had to go in docker folder structure only because system was completely out of space and even wouldn't allow me to ssh into docker container.
Just Sharing my solution... i changed the url in my browser from localhost:port to 127.0.0.1:port which resulted in very fast loading
df.filter($"state" like "T%%")
for pattern matching
df.filter($"state" === "TX")
or df.filter("state = 'TX'")
for equality
Add something to track the length and allow you to do "checks" on whether the user is adding or subtracting text. This is currently untested but something similar to this should work (especially if you have a userform).
'add this to your userform or make it a static variable if it is not part of a userform
private oldLength as integer
Private Sub txtBoxBDayHim_Change()
if ( oldlength > txboxbdayhim.textlength ) then
oldlength =txtBoxBDayHim.textlength
exit sub
end if
If txtBoxBDayHim.TextLength = 2 or txtBoxBDayHim.TextLength = 5 then
txtBoxBDayHim.Text = txtBoxBDayHim.Text + "/"
end if
oldlength =txtBoxBDayHim.textlength
End Sub
If you want actual HTTP Headers (both request and response), give hurl.it a try.
You can use the PHP command apache_request_headers()
to get the request headers and apache_response_headers()
to get the current response headers. Note that response can be changed later in the PHP script as long as content has not been served.
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
On Windows environment, you can execute py file on Python3 shell command line with the following syntax:
exec(open('absolute path to file_name').read())
Below explains how to execute a simple helloworld.py file from python shell command line
File Location: C:/Users/testuser/testfolder/helloworld.py
File Content: print("hello world")
We can execute this file on Python3.7 Shell as below:
>>> import os
>>> abs_path = 'C://Users/testuser/testfolder'
>>> os.chdir(abs_path)
>>> os.getcwd()
'C:\\Users\\testuser\\testfolder'
>>> exec(open("helloworld.py").read())
hello world
>>> exec(open("C:\\Users\\testuser\\testfolder\\helloworld.py").read())
hello world
>>> os.path.abspath("helloworld.py")
'C:\\Users\\testuser\\testfolder\\helloworld.py'
>>> import helloworld
hello world
Why complicate things when it can be done with simple jQuery like following.
$('#myModal').on('shown.bs.modal', function (e) {
console.log('myModal is shown');
// Your actual function here
})
How about, this. Not mentioned here yet.
py 2 & 3
a = {"a":2,"b":3}
a[list(a)[0]] # the first element is here
>>> 2
My personal preference is to delete the branch name after I’m done with a topic branch.
Instead of trying to use the branch name to explain the meaning of the branch, I start the subject line of the commit message in the first commit on that branch with “Branch:” and include further explanations in the body of the message if the subject does not give me enough space.
The branch name in my use is purely a handle for referring to a topic branch while working on it. Once work on the topic branch has concluded, I get rid of the branch name, sometimes tagging the commit for later reference.
That makes the output of git branch
more useful as well: it only lists long-lived branches and active topic branches, not all branches ever.
You have done the stored procedure correctly but I think you have not referenced the valido
variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido
This statement SELECT valido;
should be like this SELECT @valido;
Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido
I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.
I think android:screenOrientation="portrait"
can be used for individual activities. So use that attribute in <activity>
tag like :
<activity android:name=".<Activity Name>"
android:label="@string/app_name"
android:screenOrientation="portrait">
...
</activity>
This means that Table A can have one or more records relating to a single record in Table B.
If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:
ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id)
fk_b
: Name of the foreign key constraint, must be unique to the databaseb_id
: Name of column in Table A you are creating the foreign key relationship onb
: Name of table, in this case bid
: Name of column in Table BAfter reading the other answers, I still had trouble understanding why the set comes out un-ordered.
Mentioned this to my partner and he came up with this metaphor: take marbles. You put them in a tube a tad wider than marble width : you have a list. A set, however, is a bag. Even though you feed the marbles one-by-one into the bag; when you pour them from a bag back into the tube, they will not be in the same order (because they got all mixed up in a bag).
TL;DR
npm uninstall node-sass
npm install [email protected]
Or, if using yarn (default in newer CRA versions)
yarn remove node-sass
yarn add [email protected]
Edit2: sass-loader v10.0.5 fixes it. Problem is, you might not be using it as a project dependency, but more as a dependency of your dependencies. CRA uses a fixed version, angular-cli locks to node-sass v4 an so on.
The recommendation for now is: if you're installing just node-sass check below workaround (and the note). If you're working on a blank project and you can manage your webpack configuration (not using CRA or a CLI to scaffold your project) install latest sass-loader.
Edit: this error comes from sass-loader. There is a semver mismatch since node-sass @latest is v5.0.0 and sass-loader expects ^4.0.0.
There is an open issue on their repository with an associated fix that needs to be reviewed. Until then, refer to the solution below.
Workaround: don't install node-sass 5.0.0 yet (major version was just bumped).
Uninstall node-sass
npm uninstall node-sass
Then install the latest version (before 5.0)
npm install [email protected]
Note: LibSass (hence node-sass as well) is deprecated and dart-sass is the recommended implementation. You can use sass
instead, which is a node distribution of dart-sass compiled to pure JavaScript.
Be warned though:
Be careful using this approach. React-scripts uses sass-loader v8, which prefers node-sass to sass (which has some syntax not supported by node-sass). If both are installed and the user worked with sass, this could lead to errors on css compilation
To add to Reed Copsey's answer about using Task.FromResult
, you can improve performance even more if you cache the already completed task since all instances of completed tasks are the same:
public static class TaskExtensions
{
public static readonly Task CompletedTask = Task.FromResult(false);
}
With TaskExtensions.CompletedTask
you can use the same instance throughout the entire app domain.
The latest version of the .Net Framework (v4.6) adds just that with the Task.CompletedTask
static property
Task completedTask = Task.CompletedTask;
Unable to comment on others answers, I'll provide a bit of extra information.
If you want to revert
the last commit, you can use git revert head
. head
refers to the most recent commit in your branch.
The reason you use head~1
when using reset
is that you are telling Git to "remove all changes in the commits after" (reset --hard
) "the commit one before head" (head~1
).
reset
is to a commit, revert
is on a commit.
As AmpT pointed out, you can also use the commit SHA to identify it, rather than counting how far away from head
it is. The SHA can be found in the logs (git log
) and a variety of other ways.
You can also always use any other pointers in Git. e.g. a tag or branch. And can also use all of these fun other ways to reference commits https://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html#_specifying_revisions
Its simple try below code --
a{
outline: medium none !important;
}
If happy cheers! Good day
check for
if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
The easiest way is to use the library commands
import commands
print commands.getstatusoutput('echo "test" | wc')
After some fiddling with a script I came to this action. Copy and save it in a .bat file:
FOR /F "usebackq tokens=5" %%i IN (`netstat -aon ^| find "3306"`) DO taskkill /F /PID %%i
Change 'find "3306"' in the port number which needs to be free. Then run the file as administrator. It will kill all the processes running on this port.
I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:
import csv
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j','k']
with open('C:/test/numbers.csv', 'wb+') as myfile:
wr = csv.writer(myfile)
wr.writerow(("list1", "list2"))
rcount = 0
for row in list1:
wr.writerow((list1[rcount], list2[rcount]))
rcount = rcount + 1
myfile.close()
If you need to update user information for a specific user ID "x",
The ViewModel will initialize an instance of dbManager to access the database. The code should look like this:
@Entity
class User{
@PrimaryKey
String userId;
String username;
}
Interface UserDao{
//forUpdate
@Update
void updateUser(User user)
}
Class DbManager{
//AppDatabase gets the static object o roomDatabase.
AppDatabase appDatabase;
UserDao userDao;
public DbManager(Application application ){
appDatabase = AppDatabase.getInstance(application);
//getUserDao is and abstract method of type UserDao declared in AppDatabase //class
userDao = appDatabase.getUserDao();
}
public void updateUser(User user, boolean isUpdate){
new InsertUpdateUserAsyncTask(userDao,isUpdate).execute(user);
}
public static class InsertUpdateUserAsyncTask extends AsyncTask<User, Void, Void> {
private UserDao userDAO;
private boolean isInsert;
public InsertUpdateBrandAsyncTask(BrandDAO userDAO, boolean isInsert) {
this. userDAO = userDAO;
this.isInsert = isInsert;
}
@Override
protected Void doInBackground(User... users) {
if (isInsert)
userDAO.insertBrand(brandEntities[0]);
else
//for update
userDAO.updateBrand(users[0]);
//try {
// Thread.sleep(1000);
//} catch (InterruptedException e) {
// e.printStackTrace();
//}
return null;
}
}
}
Class UserViewModel{
DbManager dbManager;
public UserViewModel(Application application){
dbmanager = new DbMnager(application);
}
public void updateUser(User user, boolean isUpdate){
dbmanager.updateUser(user,isUpdate);
}
}
Now in your activity or fragment initialise your UserViewModel like this:
UserViewModel userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
Then just update your user item this way, suppose your userId is 1122 and userName is "xyz" which has to be changed to "zyx".
Get an userItem of id 1122 User object
User user = new user(); if(user.getUserId() == 1122){ user.setuserName("zyx"); userViewModel.updateUser(user); }
This is a raw code, hope it helps you.
Happy coding
I had a similar issue myself, I think all you need to do is git reset --hard
and you will not lose your changes or any untracked changes.
If you read the docs in git stash --help
it states that apply is "Like pop, but do not remove the state from the stash list" so the state still resides there, you can get it back.
Alternatively, if you have no conflicts, you can just git stash
again after testing your changes.
If you do have conflicts, don't worry, git reset --hard
won't lose them, as
"Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards."
Visual Studio has got now integrated support for range checking and type checking :-
Try this :- For RANGE CHECKING Before validating/checking for a particular range of numbers Switch on to design view from markup view .Then :-
View>Toolbox>Validation
Now Drag on RangeValidator to your design page where you want to show the error message(ofcourse if user is inputting out of range value) now click on your RangeValidator control . Right click and select properties . In the Properties window (It is usually opened below solution bar) select on ERROR MESSAGE . Write :-
Number must be in range.
Now select on Control to validate and select your TextboxID (or write it anyways) from the drop down.Locate Type in the property bar itself and select down Integer.
Just above it you will find maximum and minimum value .Type in your desired number .
For Type checking (without any Range)
Before validating/checking for a particular range of numbers Switch on to design view from markup view .Then :-
View>Toolbox>Validation
Now Drag on CompareValidator to your design page where you want to show the error message(ofcourse if user is inputting some text in it). now click on your CompareValidator control . Right click and select properties . In the Properties window (It is usually opened below solution bar) select on ERROR MESSAGE . Write:-
Value must be a number .
Now locate ControltoValidate option and write your controlID name in it(alternatively you can also select from drop down).Locate the Operator option and write DataTypeCheck(alternatively you can also select from drop down)in it .Again locate the Type option and write Integer in it .
That's sit.
Alternatively you can write the following code in your aspx page :- <%--to validate without any range--%>
use this line, this worked for me
mongoose.set('useUnifiedTopology', true);
The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.
For example:
char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;
execvp(cmd, argv); //This will run "ls -la" as if it were a command
The simplest way is to set the new HTML content using:
document.open();
document.write(newContent);
document.close();
If you have seaborn
installed, an easier method that does not require you to perform pivot
:
import seaborn as sns
sns.lineplot(data=df, x='x', y='y', hue='color')
Yup, this is possible of course. Here are several examples.
-- one way to do this
DECLARE @Cnt int
SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn
-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)
-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double
SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable
Smartest tried and tested way of passing data between fragments and activity is to create a variables,example:
class StorageUtil {
public static ArrayList<Employee> employees;
}
Then to pass data from fragment to activity, we do so in the onActivityCreated method:
//a field created in the sending fragment
ArrayList<Employee> employees;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
employees=new ArrayList();
//java 7 and above syntax for arraylist else use employees=new ArrayList<Employee>() for java 6 and below
//Adding first employee
Employee employee=new Employee("1","Andrew","Sam","1984-04-10","Male","Ghanaian");
employees.add(employee);
//Adding second employee
Employee employee=new Employee("1","Akuah","Morrison","1984-02-04","Female","Ghanaian");
employees.add(employee);
StorageUtil.employees=employees;
}
Now you can get the value of StorageUtil.employees from everywhere. Goodluck!
For React Native
applications while running in debug add the xml block
mentioned by @Xenolion to react_native_config.xml
located in <project>/android/app/src/debug/res/xml
Similar to the following snippet:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">localhost</domain>
<domain includeSubdomains="false">10.0.2.2</domain>
<domain includeSubdomains="false">10.0.3.2</domain>
</domain-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
Based on your screenshot i found two working solutions:
First solution: add to dependencies of your gradle module this line
compile 'com.android.support:support-annotations:27.1.1'
and sync your project
Note: if you are using Android studio 3+ change compile
to implementation
Second solution: Configure project-wide properties found in the documentation https://developer.android.com/studio/build/gradle-tips.html#configure-project-wide-properties
in project gradle add this line:
// This block encapsulates custom properties and makes them available to all
// modules in the project.
ext {
// The following are only a few examples of the types of properties you can define.
compileSdkVersion = 26
// You can also use this to specify versions for dependencies. Having consistent
// versions between modules can avoid behavior conflicts.
supportLibVersion = "27.1.1"
}
Then to access this section change compileSdkVersion
line to be
compileSdkVersion rootProject.ext.compileSdkVersion
and at dependencies
section change the imported library to be like this:
compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
and sync your project
Note: if you are using Android studio 3+ change compile
to implementation
For the difference between compile
and implementation
look at this
What's the difference between implementation and compile in gradle
Hope below helps!
PS C:\Users\aameer>$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
[datetime]$Format_date =$invoice
Now type is converted. You can use method or can access any property.
Example :$Format_date.AddDays(5)
Step 1:- Import "Dimensions" api from 'react-native'
import { Dimensions } from 'react-native';
Step 2:- Get Dimensions (Window width/height)
const { width, height } = Dimensions.get("window");
Step 3:- Use width and height variable.
<View style={{width:width,height:height/20}>
<Text>test<Text/>
</View>
using (var client = new HttpClient(handler))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, apiEndPoint)).ConfigureAwait(false);
await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
This worked for me
Try this. I've tried the solution and it works.
Dim ask = InputBox("")
If ask.Length <> 0 Then
// your code
Else
// cancel or X Button
End If
Mysql documentation says : CREATE SCHEMA is a synonym for CREATE DATABASE as of MySQL 5.0.2.
this all goes back to an ANSI standard for SQL in the mid-80s.
That standard had a "CREATE SCHEMA" command, and it served to introduce multiple name spaces for table and view names. All tables and views were created within a "schema". I do not know whether that version defined some cross-schema access to tables and views, but I assume it did. AFAIR, no product (at least back then) really implemented it, that whole concept was more theory than practice.
OTOH, ISTR this version of the standard did not have the concept of a "user" or a "CREATE USER" command, so there were products that used the concept of a "user" (who then had his own name space for tables and views) to implement their equivalent of "schema".
This is an area where systems differ.
As far as administration is concerned, this should not matter too much, because here you have differences anyway.
As far as you look at application code, you "only" have to care about cases where one application accesses tables from multiple name spaces. AFAIK, all systems support a syntax ".", and for this it should not matter whether the name space is that of a user, a "schema", or a "database".
In build.gradle change minSdkVersion 17 or later.
Just drop
<script>
myfunction();
</script>
in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.
Step 1: Turn off USB DEBUGGING in Developer Options
Step 2: Remove USB Cable
Step 3: Turn on USB Debugging(This rests USB Configurations)
Step 4: on Command Prompt enter adb kill-server and then adb start-server
Step 5: Connect the USB Cable
Step 6: Check Devices connected in Run in Android Studio(you should be able to see your device listed)
Step 7: If you want to continue running using the cable this would be good enough
(If you want to do Wireless Debugging continue with below step)
Step 8: type adb tcpip 5555. If no error is displayed remove USB Cable
Step 9: Look up IP Address of your phone from About abd then type adb connect xxx.vvv.b.n(your phone's IP)
Step 10: Check in Devices in Android Studio again and you shud see you r device in List of devices. If yes,
Updated! 3/24/2015 (scroll below hr)
lonesomeday's answer is absolutely correct, I just thought I would add this tidbit. I had made a method a while back for getting browser in Vanilla JS and eventually curved it to replace jQuery.browser
in later versions of jQuery. It does not interfere with any part of the new jQuery lib, but provides the same functionality of the traditional jQuery.browser
object, as well as some other little features.
New Extended Version!
Is much more thorough for newer browser. Also, 90+% accuracy on mobile testing! I won't say 100%, as I haven't tested on every mobile browser, but new feature adds $.browser.mobile
boolean/string. It's false if not mobile, else it will be a String name for the mobile device or browser (Best Guesss like: Android, RIM Tablet, iPod, etc...).
One possible caveat, may not work with some older (unsupported) browsers as it is completely reliant on userAgent
string.
/* quick & easy cut & paste */
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);
/* quick & easy cut & paste */
jsFiddle "jQuery Plugin: Get Browser (Extended Alt Edition)"
/** jQuery.browser_x000D_
* @author J.D. McKinstry (2014)_x000D_
* @description Made to replicate older jQuery.browser command in jQuery versions 1.9+_x000D_
* @see http://jsfiddle.net/SpYk3/wsqfbe4s/_x000D_
*_x000D_
* @extends jQuery_x000D_
* @namespace jQuery.browser_x000D_
* @example jQuery.browser.browser == 'browserNameInLowerCase'_x000D_
* @example jQuery.browser.version_x000D_
* @example jQuery.browser.mobile @returns BOOLEAN_x000D_
* @example jQuery.browser['browserNameInLowerCase']_x000D_
* @example jQuery.browser.chrome @returns BOOLEAN_x000D_
* @example jQuery.browser.safari @returns BOOLEAN_x000D_
* @example jQuery.browser.opera @returns BOOLEAN_x000D_
* @example jQuery.browser.msie @returns BOOLEAN_x000D_
* @example jQuery.browser.mozilla @returns BOOLEAN_x000D_
* @example jQuery.browser.webkit @returns BOOLEAN_x000D_
* @example jQuery.browser.ua @returns navigator.userAgent String_x000D_
*/_x000D_
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);_x000D_
/* - - - - - - - - - - - - - - - - - - - */_x000D_
_x000D_
var b = $.browser;_x000D_
console.log($.browser); // see console, working example of jQuery Plugin_x000D_
console.log($.browser.chrome);_x000D_
_x000D_
for (var x in b) {_x000D_
if (x != 'init')_x000D_
$('<tr />').append(_x000D_
$('<th />', { text: x }),_x000D_
$('<td />', { text: b[x] })_x000D_
).appendTo($('table'));_x000D_
}
_x000D_
table { border-collapse: collapse; }_x000D_
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
th { text-align: right; }_x000D_
_x000D_
textarea { height: 500px; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<table></table>
_x000D_
Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler
, which defines a method that is invoked when a proxy method is invoked.
You create them by using the call
Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
The arguments are:
classLoader
. Once the class is generated, it is loaded with this class loader.interfaces
. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.invocationHandler
. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler
. When a method from any of the supported interfaces, or hashCode
, equals
, or toString
, is invoked, the method invoke
is invoked on the handler, passing the Method
object for the method to be invoked and the arguments passed.For more on this, see the documentation for the Proxy
class.
Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.
You can simply achieve this using oninvalid attribute, checkout this demo code
<form>
<input type="email" pattern="[^@]*@[^@]" required oninvalid="this.setCustomValidity('Put here custom message')"/>
<input type="submit"/>
</form>
Codepen Demo: https://codepen.io/akshaykhale1992/pen/yLNvOqP
To add the new repo location,
git remote add new_repo_name new_repo_url
Then push the content to the new location
git push new_repo_name master
Finally remove the old one
git remote rm origin
After that you can do what bdonlan said and edit the.git/config file to change the new_repo_name to origin. If you don't remove the origin (original remote repository), you can simply just push changes to the new repo with
git push new_repo_name master
Don't know exactly what kind of dataset you have, so I provide general answer.
x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
x y
1 1 1
2 2 2
3 NA 3
4 3 NA
5 4 6
6 5 8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
x y
1 1 1
2 2 2
5 4 6
6 5 8
Fastest way I think
$newArray = array();
for($count == 0;$row = mysql_fetch_assoc($getResults);$count++)
{
foreach($row as $key => $value)
{
$newArray[$count]{$key} = $row[$key];
}
}
List<string> values =new list<string>();
foreach(ListItem Item in ChkList.Item)
{
if(Item.Selected)
values.Add(item.Value);
}
Ajax Submit form with out page refresh by using jquery ajax method first include library jquery.js and jquery-form.js then create form in html:
<form action="postpage.php" method="POST" id="postForm" >
<div id="flash_success"></div>
name:
<input type="text" name="name" />
password:
<input type="password" name="pass" />
Email:
<input type="text" name="email" />
<input type="submit" name="btn" value="Submit" />
</form>
<script>
var options = {
target: '#flash_success', // your response show in this ID
beforeSubmit: callValidationFunction,
success: YourResponseFunction
};
// bind to the form's submit event
jQuery('#postForm').submit(function() {
jQuery(this).ajaxSubmit(options);
return false;
});
});
function callValidationFunction()
{
// validation code for your form HERE
}
function YourResponseFunction(responseText, statusText, xhr, $form)
{
if(responseText=='success')
{
$('#flash_success').html('Your Success Message Here!!!');
$('body,html').animate({scrollTop: 0}, 800);
}else
{
$('#flash_success').html('Error Msg Here');
}
}
</script>
I have a list of positions of array to retrieve ,This worked for me.
public void create_list_to_add_group(ArrayList<Integer> arrayList_loc) {
//In my case arraylist_loc is the list of positions to retrive from
// contact_names
//arraylist and phone_number arraylist
ArrayList<String> group_members_list = new ArrayList<>();
ArrayList<String> group_members_phone_list = new ArrayList<>();
int size = arrayList_loc.size();
for (int i = 0; i < size; i++) {
try {
int loc = arrayList_loc.get(i);
group_members_list.add(contact_names_list.get(loc));
group_members_phone_list.add(phone_num_list.get(loc));
} catch (Exception e) {
e.printStackTrace();
}
}
Log.e("Group memnbers list", " " + group_members_list);
Log.e("Group memnbers num list", " " + group_members_phone_list);
}
Does it really have to be a thread, or can it be a task too?
if so, the easiest way is:
Task.Factory.StartNew(() => SecondFoo())
-F
is an argument to awk
itself:
$echo "1: " | awk -F":" '/1/ {print $1}'
1
If I read this correctly, it will be a requirement to use semicolons to end TSQL statements. http://msdn.microsoft.com/en-us/library/ms143729%28v=sql.120%29.aspx
EDIT: I found a plug-in for SSMS 2008R2 that will format your script and add the semicolons. I think it is still in beta though...
http://www.tsqltidy.com/tsqltidySSMSAddin.aspx
EDIT: I found an even better free tool/plugin called ApexSQL... http://www.apexsql.com/
Source code:
public long fileSize(File root) {
if(root == null){
return 0;
}
if(root.isFile()){
return root.length();
}
try {
if(isSymlink(root)){
return 0;
}
} catch (IOException e) {
e.printStackTrace();
return 0;
}
long length = 0;
File[] files = root.listFiles();
if(files == null){
return 0;
}
for (File file : files) {
length += fileSize(file);
}
return length;
}
private static boolean isSymlink(File file) throws IOException {
File canon;
if (file.getParent() == null) {
canon = file;
} else {
File canonDir = file.getParentFile().getCanonicalFile();
canon = new File(canonDir, file.getName());
}
return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}
Another option is CSVLogger: https://keras.io/callbacks/#csvlogger. It creates a csv file appending the result of each epoch. Even if you interrupt training, you get to see how it evolved.
I got asked this question recently, and whilst I couldn't get O(N) during it, I had a different approach (unfortunately O(N^2)) but thought I'd share anyway.
Convert to List<Integer>
first.
Loop through original array array.length()
times.
Use a while
loop to multiple the next set of required numbers:
while (temp < list.size() - 1) {
res *= list.get(temp);
temp++;
}
Then add res
to a new array (which of course you've declared earlier), then add the value at array[i]
to the List
, and continue so forth.
I know this won't be of great use, but it's what I came up with under the pressures of an interview :)
int[] array = new int[]{1, 2, 3, 4, 5};
List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());
int[] newarray = new int[array.length];
int res = 1;
for (int i = 0; i < array.length; i++) {
int temp = i;
while (temp < list.size() - 1) {
res *= list.get(temp);
temp++;
}
newarray[i] = res;
list.add(array[i]);
res = 1;
}
Output: [24, 120, 60, 40, 30]
UPDATE: Supposedly, zIndex
has been added to the react-native
library. I've been trying to get it to work without success. Check here for details of the fix.
Ive just been searching for a solution and come across Spreadsheetlight
which looks very promising. Its open source and available as a nuget package.
It looks like you're writing PHP, in which case you want:
<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>
Notice that the ('us'=>'United', 'ca'=>'canada')
needs to be a parameter to the array function in PHP.
Most programming languages that support associative arrays or dictionaries use arr['key']
to retrieve the item specified by 'key'
For instance:
ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
=> {"us"=>"USA", "ca"=>"Canada"}
ruby-1.9.1-p378 > h['ca']
=> "Canada"
>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'
#
class P
{
static void Main()
{
var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
System.Console.WriteLine(d["ca"]);
}
}
t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables
While it is really not possible to use a char
or a string
as the base for an enum, i think this is not what you really like to do.
Like you mentioned you'd like to have an enum of possibilities and show a string representation of this within a combo box. If the user selects one of these string representations you'd like to get out the corresponding enum. And this is possible:
First we have to link some string to an enum value. This can be done by using the DescriptionAttribute
like it is described here or here.
Now you need to create a list of enum values and corresponding descriptions. This can be done by using the following method:
/// <summary>
/// Creates an List with all keys and values of a given Enum class
/// </summary>
/// <typeparam name="T">Must be derived from class Enum!</typeparam>
/// <returns>A list of KeyValuePair<Enum, string> with all available
/// names and values of the given Enum.</returns>
public static IList<KeyValuePair<T, string>> ToList<T>() where T : struct
{
var type = typeof(T);
if (!type.IsEnum)
{
throw new ArgumentException("T must be an enum");
}
return (IList<KeyValuePair<T, string>>)
Enum.GetValues(type)
.OfType<T>()
.Select(e =>
{
var asEnum = (Enum)Convert.ChangeType(e, typeof(Enum));
return new KeyValuePair<T, string>(e, asEnum.Description());
})
.ToArray();
}
Now you'll have a list of key value pairs of all enums and their description. So let's simply assign this as a data source for a combo box.
var comboBox = new ComboBox();
comboBox.ValueMember = "Key"
comboBox.DisplayMember = "Value";
comboBox.DataSource = EnumUtilities.ToList<Separator>();
comboBox.SelectedIndexChanged += (sender, e) =>
{
var selectedEnum = (Separator)comboBox.SelectedValue;
MessageBox.Show(selectedEnum.ToString());
}
The user sees all the string representations of the enum and within your code you'll get the desired enum value.
This may work for you:
select t1.*
from table t1
join (select t2.Chromosome, t2.Locus
from table2
group by t2.Chromosome, t2.Locus
having count(*) > 1) u on u.Chromosome = t1.Chromosome and u.Locus = t1.Locus
You could use this function:
function RefreshTable(tableId, urlData)
{
//Retrieve the new data with $.getJSON. You could use it ajax too
$.getJSON(urlData, null, function( json )
{
table = $(tableId).dataTable();
oSettings = table.fnSettings();
table.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
table.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
});
}
Dont' forget to call it after your delete function has succeded.
This works for me in Outlook:
<img src="image.jpg" width="120" style="display:block;width:100%" />
I hope it works for you.
its very true on oracle as well as sql is "users" is a reserved words just change it , it will serve u the best if u like change it to this
UPDATE system_info set field_value = 'NewValue'
FROM system_users users JOIN system_info info ON users.role_type = info.field_desc
where users.user_name = 'uname'
I wrote a shell script for filtering logcat by package name, which I think is more reliable than using
ps | grep com.example.package | cut -c10-15
It uses /proc/$pid/cmdline to find out the actual pid, then do a grep on logcat
What you asked for is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
The easiest way I can think of solving this is using the tables included in GitHub's flavored markdown.
To your specific example it would look something like this:
Solarized dark | Solarized Ocean
:-------------------------:|:-------------------------:
![](https://...Dark.png) | ![](https://...Ocean.png)
This creates a table with Solarized Dark and Ocean as headers and then contains the images in the first row. Obviously you would replace the ...
with the real link. The :
s are optional (They just center the content in the cells, which is kinda unnecessary in this case). Also you might want to downsize the images so they will display better side-by-side.
Here is an idea as you may have multiple newline in a textbox:
var text=document.getElementById('post-text').value.split('\n');
var html = text.join('<br />');
This HTML value will preserve newline. Hope this helps.
In Sequelize version 5 you might also can use this way (full use Operator Sequelize) :
var condition =
{
[Op.or]: [
{
LastName: {
[Op.eq]: "Doe"
},
},
{
FirstName: {
[Op.or]: ["John", "Jane"]
}
},
{
Age:{
[Op.gt]: 18
}
}
]
}
And then, you must include this :
const Op = require('Sequelize').Op
and pass it in :
Student.findAll(condition)
.success(function(students){
//
})
It could beautifully generate SQL like this :
"SELECT * FROM Student WHERE LastName='Doe' OR FirstName in ("John","Jane") OR Age>18"
According to the official site. These are the two ways
<div>
{/* Comment goes here */}
Hello, {name}!
</div>
Second Example:
<div>
{/* It also works
for multi-line comments. */}
Hello, {name}!
</div>
Here is the link: https://reactjs.org/docs/faq-build.html#how-can-i-write-comments-in-jsx
You can just use the pipe on its own:
"string1|string2"
for example:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));
Output:
blah, blah, string3
The main reason to use parentheses is to limit the scope of the alternatives:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));
has the same output. but if you just do this:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));
you get:
blah, stringblah, string3
because you've said "string1" or "2".
If you don't want to capture that part of the expression use ?:
:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));
I know this question already has some good answers but I think my solution is worth of sharing.
It works for both std::map
and std::vector<std::pair<T, U>>
and is available from C++11.
template <typename ForwardIterator, typename Key>
bool contains_key(ForwardIterator first, ForwardIterator last, Key const key) {
using ValueType = typename std::iterator_traits<ForwardIterator>::value_type;
auto search_result = std::find_if(
first, last,
[&key](ValueType const& item) {
return item.first == key;
}
);
if (search_result == last) {
return false;
} else {
return true;
}
}
There is no definitive answer to this, as each browser has its own configuration for this, and this configuration may be changed. If you search on the internet you can find ways to change this limit (usually they're branded as "performance enhancement methods.") It might be worth advising your users to do so if it is required by your website.
The "Leader key" is a way of extending the power of VIM's shortcuts by using sequences of keys to perform a command. The default leader key is backslash. Therefore, if you have a map of <Leader>Q, you can perform that action by typing \Q.
The question has already been answered but I thought I would also let you know that rather than using the native PHP $_POST I reccomend you use the CodeIgniter input class so your controller code would be
function post_action()
{
if($this->input->post('textbox') == "")
{
$message = "You can't send empty text";
}
else
{
$message = $this->input->post('textbox');
}
echo $message;
}
$arr = array(1, 'a', 3, 4 => 1, 'b' => 1);
foreach ($arr as $key => $val) {
echo "{$key} = {$val}" . (end(array_keys($arr))===$key ? '' : ', ');
}
// output: 0 = 1, 1 = a, 2 = 3, 4 = 1, b = 1
You can do
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();
or (using Method reference)
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();
First You need to verify the base, small and thumbnail image are selected in Magento admin.
admin->catalog->manage product->product->image
Then select your image roles(base,small,thumbnail)
Then you call the image using
echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(163, 100);
Hope this helps you.
Do this:
date('Y-m-d', strtotime('dd/mm/yyyy'));
But make sure 'dd/mm/yyyy' is the actual date.
One other (and an even shorter) possibility. If you're inside drawRect, something like the following:
[[UIColor blackColor] setFill];
UIRectFill((CGRect){0,200,rect.size.width,1});
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
For unstaging all the files in your last commit -
git reset HEAD~
The body hasn't been defined at this point yet. In general, you want to create all elements before you execute javascript that uses these elements. In this case you have some javascript in the head
section that uses body
. Not cool.
You want to wrap this code in a window.onload
handler or place it after the <body>
tag (as mentioned by e-bacho 2.0).
<head>
<title>Javascript Tests</title>
<script type="text/javascript">
window.onload = function() {
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
}
</script>
</head>
You could have probably concluded your question after the second paragraph, rather than calling people "insane" simply because they have a different viewpoint than you do and otherwise trying to mock professionals who may have a very good reason for feeling the way that they do.
As to your question, while there are certainly situations where a cursor may be called for, in my experience developers decide that a cursor "must" be used FAR more often than is actually the case. The chance of someone erring on the side of too much use of cursors vs. not using them when they should is MUCH higher in my opinion.
Try the following, note that when user refreshes the page, the value is "Male" again, data should be stored on database.
<p id="pTest">Male</p>
<button>change</button>
<script>
$('button').click(function(){
$('#pTest').text('test')
})
</script>
You can just clone it and replace it with itself, with all events still attached:
<input type="file" id="control">
and
var input = $("#control");
function something_happens() {
input.replaceWith(input.val('').clone(true));
};
Thanks : Css-tricks.com
Here's a solution using xml_grep (because xpath wasn't part of our distributable and I didn't want to add it to all production machines)...
If you are looking for a specific setting in an XML file, and if all elements at a given tree level are unique, and there are no attributes, then you can use this handy function:
# File to be parsed
xmlFile="xxxxxxx"
# use xml_grep to find settings in an XML file
# Input ($1): path to setting
function getXmlSetting() {
# Filter out the element name for parsing
local element=`echo $1 | sed 's/^.*\///'`
# Verify the element is not empty
local check=${element:?getXmlSetting invalid input: $1}
# Parse out the CDATA from the XML element
# 1) Find the element (xml_grep)
# 2) Remove newlines (tr -d \n)
# 3) Extract CDATA by looking for *element> CDATA <element*
# 4) Remove leading and trailing spaces
local getXmlSettingResult=`xml_grep --cond $1 $xmlFile 2>/dev/null | tr -d '\n' | sed -n -e "s/.*$element>[[:space:]]*\([^[:space:]].*[^[:space:]]\)[[:space:]]*<\/$element.*/\1/p"`
# Return the result
echo $getXmlSettingResult
}
#EXAMPLE
logPath=`getXmlSetting //config/logs/path`
check=${logPath:?"XML file missing //config/logs/path"}
This will work with this structure:
<config>
<logs>
<path>/path/to/logs</path>
<logs>
</config>
It will also work with this (but it won't keep the newlines):
<config>
<logs>
<path>
/path/to/logs
</path>
<logs>
</config>
If you have duplicate <config> or <logs> or <path>, then it will only return the last one. You can probably modify the function to return an array if it finds multiple matches.
FYI: This code works on RedHat 6.3 with GNU BASH 4.1.2, but I don't think I'm doing anything particular to that, so should work everywhere.
NOTE: For anybody new to scripting, make sure you use the right types of quotes, all three are used in this code (normal single quote '=literal, backward single quote `=execute, and double quote "=group).
I found the console output of my job in the browser at the following location:
http://[Jenkins URL]/job/[Job Name]/default/[Build Number]/console
NPOI For Excel 2003 Open Source http://www.leniel.net/2009/07/creating-excel-spreadsheets-xls-xlsx-c.html
Your and
should be a &&
in the where
clause.
where epl.DepartAirportAfter > sd.UTCDepartureTime
and epl.ArriveAirportBy > sd.UTCArrivalTime
should be
where epl.DepartAirportAfter > sd.UTCDepartureTime
&& epl.ArriveAirportBy > sd.UTCArrivalTime
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
This is how I solved it
if recursive:
items = os.walk(target_directory)
else:
items = [next(os.walk(target_directory))]
...
The function makes the second one asynchronous.
The first one forces the program to wait for each line to finish it's run before the next one can continue. The second one allows each line to run together (and independently) at once.
Languages and frameworks (js, node.js) that allow asynchronous or concurrency is great for things that require real time transmission (eg. chat, stock applications).
If you still want to show the item but make it not clickable and look disabled with CSS:
CSS:
.disabled {
pointer-events:none; //This makes it not clickable
opacity:0.6; //This grays it out to look disabled
}
HTML:
<li class="disabled">Disabled List Item</li>
Also, if you are using BootStrap, they already have a class called disabled for this purpose. See this example.
As @LV98 pointed out, users could change this on the client side and submit a selection you weren't expecting. You will want to validate at the server as well.
Technical differences are a consequence of the goal of each one (OpenJDK is meant to be the reference implementation, open to the community, while Oracle is meant to be a commercial one)
They both have "almost" the same code of the classes in the Java API; but the code for the virtual machine itself is actually different, and when it comes to libraries, OpenJDK tends to use open libraries while Oracle tends to use closed ones; for instance, the font library.
Just use the following code. It is really useful to send email via Java, and it works:
import java.util.*;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.Provider;
import javax.mail.internet.*;
public class Main {
public static void main(String[] args) {
final String username="[email protected]";
final String password="password";
Properties prop=new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
String body="Dear Renish Khunt Welcome";
String htmlBody = "<strong>This is an HTML Message</strong>";
String textBody = "This is a Text Message.";
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
message.setText(htmlBody);
message.setContent(textBody, "text/html");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
To remove everything before the first /
input = input.Substring(input.IndexOf("/"));
To remove everything after the first /
input = input.Substring(0, input.IndexOf("/") + 1);
To remove everything before the last /
input = input.Substring(input.LastIndexOf("/"));
To remove everything after the last /
input = input.Substring(0, input.LastIndexOf("/") + 1);
An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:
To remove everything after the first /
input = input.Remove(input.IndexOf("/") + 1);
To remove everything after the last /
input = input.Remove(input.LastIndexOf("/") + 1);
You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.
You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig
. It will give out some information and your local IP should look like 192.168.1.x.
Install
pip install Pillow
Then, Just import in your file like,
from PIL import Image
I am using windows. It is working for me.
NOTE:
Pillow is a functional drop-in replacement for the Python Imaging Library. To run your existing PIL-compatible code with Pillow, it needs to be modified to import the Imaging module from the PIL namespace instead of the global namespace.
i.e. change:
import Image
to:
from PIL import Image
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
I was getting the same error and nothing was wrong with my java files and packages. Later I noticed that the folder name WEB-INF was written like this "WEB_INF". So correcting just the folder name solved the issue
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
You can use SQLiteOpenHelper's onUpgrade
method. In the onUpgrade method, you get the oldVersion as one of the parameters.
In the onUpgrade
use a switch
and in each of the case
s use the version number to keep track of the current version of database.
It's best that you loop over from oldVersion
to newVersion
, incrementing version
by 1 at a time and then upgrade the database step by step. This is very helpful when someone with database version 1 upgrades the app after a long time, to a version using database version 7 and the app starts crashing because of certain incompatible changes.
Then the updates in the database will be done step-wise, covering all possible cases, i.e. incorporating the changes in the database done for each new version and thereby preventing your application from crashing.
For example:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
case 1:
String sql = "ALTER TABLE " + TABLE_SECRET + " ADD COLUMN " + "name_of_column_to_be_added" + " INTEGER";
db.execSQL(sql);
break;
case 2:
String sql = "SOME_QUERY";
db.execSQL(sql);
break;
}
}
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
The easiest way to overwrite a text file is to use a public static field.
this will overwrite the file every time because your only using false the first time through.`
public static boolean appendFile;
Use it to allow only one time through the write sequence for the append field of the write code to be false.
// use your field before processing the write code
appendFile = False;
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
//change this line to read this
// f2 = new FileWriter(fnew,false);
// to read this
f2 = new FileWriter(fnew,appendFile); // important part
f2.write(source);
// change field back to true so the rest of the new data will
// append to the new file.
appendFile = true;
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use undocumented method android.app.ActivityThread.currentPackageName()
:
Class<?> clazz = Class.forName("android.app.ActivityThread");
Method method = clazz.getDeclaredMethod("currentPackageName", null);
String appPackageName = (String) method.invoke(clazz, null);
Caveat: This must be done on the main thread of the application.
Thanks to this blog post for the idea: http://blog.javia.org/static-the-android-application-package/ .
Here's a code that really works for IE and FF (at least):
<html>
<head>
<title>Test</title>
<style type="text/css">
table{
width: 400px;
}
tbody {
height: 100px;
overflow: scroll;
}
div {
height: 100px;
width: 400px;
position: relative;
}
tr.alt td {
background-color: #EEEEEE;
}
</style>
<!--[if IE]>
<style type="text/css">
div {
overflow-y: scroll;
overflow-x: hidden;
}
thead tr {
position: absolute;
top: expression(this.offsetParent.scrollTop);
}
tbody {
height: auto;
}
</style>
<![endif]-->
</head>
<body>
<div >
<table border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th style="background: lightgreen;">user</th>
<th style="background: lightgreen;">email</th>
<th style="background: lightgreen;">id</th>
<th style="background: lightgreen;">Y/N</th>
</tr>
</thead>
<tbody align="center">
<!--[if IE]>
<tr>
<td colspan="4">on IE it's overridden by the header</td>
</tr>
<![endif]-->
<tr>
<td>user 1</td>
<td>[email protected]</td>
<td>1</td>
<td>Y</td>
</tr>
<tr class="alt">
<td>user 2</td>
<td>[email protected]</td>
<td>2</td>
<td>N</td>
</tr>
<tr>
<td>user 3</td>
<td>[email protected]</td>
<td>3</td>
<td>Y</td>
</tr>
<tr class="alt">
<td>user 4</td>
<td>[email protected]</td>
<td>4</td>
<td>N</td>
</tr>
<tr>
<td>user 5</td>
<td>[email protected]</td>
<td>5</td>
<td>Y</td>
</tr>
<tr class="alt">
<td>user 6</td>
<td>[email protected]</td>
<td>6</td>
<td>N</td>
</tr>
<tr>
<td>user 7</td>
<td>[email protected]</td>
<td>7</td>
<td>Y</td>
</tr>
<tr class="alt">
<td>user 8</td>
<td>[email protected]</td>
<td>8</td>
<td>N</td>
</tr>
</tbody>
</table>
</div>
</body></html>
I've changed the original code to make it clearer and also to put it working fine in IE and also FF..
Original code HERE
The main advantages are syntactic:
You are unlikely to see any performance benefits with ES6 modules. You will still need an extra library to bundle the modules, even when there is full support for ES6 features in the browser.
W3Schools is your friend: http://www.w3schools.com/php/func_filesystem_fgets.asp
And here: http://php.net/manual/en/function.fopen.php has more info on fopen including what the modes are.
What W3Schools says:
<?php
$file = fopen("test.txt","r");
while(! feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
fopen opens the file (in this case test.txt with mode 'r' which means read-only and places the pointer at the beginning of the file)
The while loop tests to check if it's at the end of file (feof) and while it isn't it calls fgets which gets the current line where the pointer is.
Continues doing this until it is the end of file, and then closes the file.
Try this:
!unpack file.zip
If its now working or file is 7z try below
!apt-get install p7zip-full
!p7zip -d file_name.tar.7z
!tar -xvf file_name.tar
Or
!pip install pyunpack
!pip install patool
from pyunpack import Archive
Archive(‘file_name.tar.7z’).extractall(‘path/to/’)
!tar -xvf file_name.tar
****In Swift 3****
To create border
btnName.layer.borderWidth = 1
btnName.layer.borderColor = UIColor.black.cgColor
To make corner rounded
btnName.layer.cornerRadius = 5
You want to do this:
git add -u
git reset HEAD path/to/file
git commit
Be sure and do this from the top level of the repo; add -u
adds changes in the current directory (recursively).
The key line tells git to reset the version of the given path in the index (the staging area for the commit) to the version from HEAD (the currently checked-out commit).
And advance warning of a gotcha for others reading this: add -u
stages all modifications, but doesn't add untracked files. This is the same as what commit -a
does. If you want to add untracked files too, use add .
to recursively add everything.
Modified regex for answer above
var isSafari = /^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent);
To avoid problems with the batch parser (e.g. exclamation point), look at Problem with search and replace batch file.
Following modification of aflat's script will include special characters like exclamation points.
@echo off
setlocal DisableDelayedExpansion
set INTEXTFILE=test.txt
set OUTTEXTFILE=test_out.txt
set SEARCHTEXT=bath
set REPLACETEXT=hello
set OUTPUTLINE=
for /f "tokens=1,* delims=¶" %%A in ( '"type %INTEXTFILE%"') do (
SET string=%%A
setlocal EnableDelayedExpansion
SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!
>> %OUTTEXTFILE% echo(!modified!
endlocal
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%
I came across this problem too. I made 2 commit
and wanted to rollback and delete both commits.
$ hg rollback
But hg rollback
just rolls back to the last commit, not the 2 commits. At that time I did not realize this and I changed the code.
When I found hg rollback
had just rolled back one commit, I found I could use hg strip #changeset#
. So, I used hg log -l 10
to find the latest 10 commits and get the right changeset I wanted to strip
.
$ hg log -l 10
changeset: 2499:81a7a8f7a5cd
branch: component_engine
tag: tip
user: myname<[email protected]>
date: Fri Aug 14 12:22:02 2015 +0800
summary: get runs from sandbox
changeset: 2498:9e3e1de76127
branch: component_engine
user: other_user_name<[email protected]>
date: Mon Aug 03 09:50:18 2015 +0800
summary: Set current destination to a copy incoming exchange
......
$ hg strip 2499
abort: local changes found
What does abort: local changes found
mean? It means that hg
found changes to the code that haven't been committed yet. So, to solve this, you should hg diff
to save the code you have changed and hg revert
and hg strip #changeset#
. Just like this:
$ hg diff > /PATH/TO/SAVE/YOUR/DIFF/FILE/my.diff
$ hg revert file_you_have_changed
$ hg strip #changeset#
After you have done the above, you can patch
the diff file and your code can be added back to your project.
$ patch -p1 < /PATH/TO/SAVE/YOUR/DIFF/FILE/my.diff
Scroll down on that page and you'll see:
Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.
That's the SQLEXPRWT_x64_ENU.exe
download.... (WT = with tools)
Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.
That's the SQLEXPRADV_x64_ENU.exe
download ... (ADV = Advanced Services)
The SQLEXPR_x64_ENU.exe
file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.
PHP-FPM is a service that spawns new PHP processes when needed, usually through a fast-cgi module like nginx. You can tell (with a margin of error) by just checking the init.d script e.g. "sudo /etc/init.d/php-fpm status"
What port or unix file socket is being used is up to the configuration, but often is just TCP port 9000. i.e. 127.0.0.1:9000
The best way to tell if it is running correctly is to have nginx running, and setup a virtual host that will fast-cgi pass to PHP-FPM, and just check it with wget or a browser.
I suggest using ES5 array methods:
["myCircle1","myCircle2","myCircle3","myCircle4"] // Array of IDs
.map(document.getElementById, document) // Array of elements
.forEach(doStuff);
Then doStuff
will be called once for each element, and will receive 3 arguments: the element, the index of the element inside the array of elements, and the array of elements.
You can use Redirect::away($url)
This tutorial displays splash screen for 2 seconds. You can easily change it to suit your needs.
- (void)showSplash {
UIViewController *modalViewController = [[UIViewController alloc] init];
modalViewController.view = modelView;
[self presentModalViewController:modalViewController animated:NO];
[self performSelector:@selector(hideSplash) withObject:nil afterDelay:yourDelay];
}
It always get's me worried when mixing maths with date functions (it's so easy to miss some leap year other detail). Say you have:
var d = new Date();
I would suggest using the following, days will be saved in day
:
for(var day = d.getDate(); d.getMonth(); day += d.getDate())
d.setDate(0);
Can't see any reason why this wouldn't work just fine (and I wouldn't be so worried about the few iterations since this will not be used so intensively).
Another one with a different concept: http://www.klausbasan.de/misc/telnet/index.html
In my case I had code like this:
function.call(context, arg);
I got error message under IE
TypeError: Object doesn't support property or method 'error'
In the body of 'function' I had "console.error" and it turns that console object is undefined when your console is closed. I have fixed this by checking if console and console.error are defined
Hope my scenario can help someone else.
I had the same problem with the package bcrypt. First, I have tried with npm i -g node-gyp
as suggested by Anne but the problem persisted. Then I read again the error message to have a better understanding of the problem and discovered that the script fails to build the package from scratch - since a precompiled version doesn't exist. In particular, it can't find the g++ command so I solved installing the build-essential
package with sudo apt install build-essential -y
.
If you want a real timer you need to use the date object.
Calculate the difference.
Format your string.
window.onload=function(){
var start=Date.now(),r=document.getElementById('r');
(function f(){
var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
if(diff>3e5){
start=Date.now()
}
setTimeout(f,1e3);
})();
}
Example
not so precise timer
var time=5*60,r=document.getElementById('r'),tmp=time;
setInterval(function(){
var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
tmp!=0||(tmp=time);
},1000);
Open app/build.gradle file
Change buildToolsVersion
to buildToolsVersion "26.0.2"
change compile 'com.android.support:appcompat
to compile 'com.android.support:appcompat-v7:26.0.2'
In my case I only wanted the image to behave responsively at mobile scale so I created a css style .myimgrsfix that only kicks in at mobile scale
.myimgrsfix {
@media(max-width:767px){
width:100%;
}
}
and applied that to the image <img class='img-responsive myimgrsfix' src='whatever.gif'>
The entire confusion is caused since Google chose non-intuivitive names instead of something as follows:
onCreateAndPrepareToDisplay() [instead of onCreate() ]
onPrepareToDisplay() [instead of onRestart() ]
onVisible() [instead of onStart() ]
onBeginInteraction() [instead of onResume() ]
onPauseInteraction() [instead of onPause() ]
onInvisible() [instead of onStop]
onDestroy() [no change]
The Activity Diagram can be interpreted as:
I have had the same error but b/c of diff reason. Using Entity framework. One more thing I need to add here before I share my code and solution, I had a break point on controller method but it was not breaking there, just throwing exception 500 internal server error.
I was posting data from view to controller through ajax (http post). The model I was expecting as a parameter was a class. It was inherited with some other class.
public class PurchaseOrder : CreateUpdateUserInfo
{
public PurchaseOrder()
{
this.Purchase_Order_Items = new List<clsItem>();
}
public int purchase_order_id { get; set; }
public Nullable<int> purchase_quotation_id { get; set; }
public int supplier_id { get; set; }
public decimal flat_discount { get; set; }
public decimal total { get; set; }
public decimal net_payable { get; set; }
public bool is_payment_complete { get; set; }
public decimal sales_tax { get; set; }
public DateTime CreatedOn { get; set; }
public int CreatorUserID { get; set; }
public DateTime UpdatedOn { get; set; }
public int UpdatorUserID { get; set; }
public bool IsDeleted { get; set; }
public List<clsItem> Purchase_Order_Items { get; set; }
}
public class CreateUpdateUserInfo
{
public DateTime CreatedOn { get; set; }
public int CreatorUserID { get; set; }
public string CreatorUserName { get; set; }
public DateTime UpdatedOn { get; set; }
public int UpdatorUserID { get; set; }
public string UpdatorUserName { get; set; }
public bool IsDeleted { get; set; }
}
and in view
var model = {
supplier_id : isNaN($scope.supplierID) || 0 ? null : $scope.supplierID,
flat_discount : 0,
total : $scope.total,
net_payable : $scope.total,
is_payment_complete : true,
sales_tax:0,
Purchase_Order_Item: $scope.items
};
var obj = {
method: 'POST',
url: 'Purchase/SaveOrder',
dataType: 'json',
data: JSON.stringify(model),
headers: { "Content-Type": "application/json" }
};
var request = $rootScope.AjaxRequest(obj);
request.then(function (response) {
var isError = response.data.MessageType === 1;
$rootScope.bindToaster(response.data.MessageType,response.data.Message);
//$('html, body').animate({ scrollTop: 0 }, 'slow');
if(!isError){
//$scope.supplierID =undefined;
}
}, function (response) {
$rootScope.bindToaster(2,response.data);
console.log(response);
});
Simply removed duplicated fields from PurchaseOrder class and it worked like a charm.
I do not use github plugin, but from the introduction page, it is more or less like gerrit-trigger plugin.
You can install git plugin, which can help you checkout your projects, if you want to include multi-projects in one jenkins job, just add Repository into your job.
You can declare SqlConnection
and SqlCommand
instances at global level so that you can use it through out the class. Connection string is in Web.Config
.
SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();
Now you can use the below method to pass values to Stored Procedure and get the DataSet
.
public DataSet GetDataSet(string paramValue)
{
sqlcomm.Connection = sqlConn;
using (sqlConn)
{
try
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
// This will be your input parameter and its value
sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);
// You can retrieve values of `output` variables
var returnParam = new SqlParameter
{
ParameterName = "@Error",
Direction = ParameterDirection.Output,
Size = 1000
};
sqlcomm.Parameters.Add(returnParam);
// Name of stored procedure
sqlcomm.CommandText = "StoredProcedureName";
da.SelectCommand = sqlcomm;
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
}
}
catch (SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
return new DataSet();
}
The following is the sample of connection string in config file
<connectionStrings>
<add name="SqlConnector"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
providerName="System.Data.SqlClient" />
</connectionStrings>
Automatic proxy detection is a process by which a Web proxy server is identified by the system and used to send requests on behalf of the client. This feature is also known as Web Proxy Auto-Discovery (WPAD). When automatic proxy detection is enabled, the system attempts to locate a proxy configuration script that is responsible for returning the set of proxies that can be used for the request.
I have created the Fade in and Fade Out animation for Dialogbox using ChrisJD code.
Inside res/style.xml
<style name="AppTheme" parent="android:Theme.Light" />
<style name="PauseDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowAnimationStyle">@style/PauseDialogAnimation</item>
</style>
<style name="PauseDialogAnimation">
<item name="android:windowEnterAnimation">@anim/fadein</item>
<item name="android:windowExitAnimation">@anim/fadeout</item>
</style>
Inside anim/fadein.xml
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
Inside anim/fadeout.xml
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/anticipate_interpolator"
android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />
MainActivity
Dialog imageDiaglog= new Dialog(MainActivity.this,R.style.PauseDialog);
Sometimes there will be some stale Jenkins processes, so ps -ef | grep jenkins
kill all of them. Restart as described in previous answers, and it will be clean.
ps -ef | grep jenkins
sudo kill -kill <pid>
I recently ran into this kinda issue, where I need to communicate between client and server using websocket in a PHP based codeigniter project.
I resolved this issue by adding my port(node app running on) into Allow incoming TCP ports
& Allow outgoing TCP ports
lists.
You can find these configurations in Firewall Configurations
in your server's WHM panel.
Just call moment as a function without any arguments:
moment()
For timezone information with moment, look at the moment-timezone
package: http://momentjs.com/timezone/
An old question, but I'll answer anyway. The answer to the actual question asked is that the bare return is redundant and should be left out.
Furthermore, the suggested value is false for the following reason:
if (ret<0) return;
Redefining a C reserved word as a macro is a bad idea on the face of it, but this particular suggestion is simply unsupportable, both as an argument and as code.
class PersonDB
{
string[] list = { "John", "Sam", "Dave" };
public void Process(ProcessPersonDelegate f)
{
foreach(string s in list) f(s);
}
}
The second class is Client, which will use the storage class. It has a Main method that creates an instance of PersonDB, and it calls that object’s Process method with a method that is defined in the Client class.
class Client
{
static void Main()
{
PersonDB p = new PersonDB();
p.Process(PrintName);
}
static void PrintName(string name)
{
System.Console.WriteLine(name);
}
}
You need to understand java generics. You have a list of ClientThread
but trying to get String
. You have other errors, but this one is very basic.
Use Method to Serialize and Deserialize Collection object from memory. This works on Collection Data Types. This Method will Serialize collection of any type to a byte stream. Create a Seperate Class SerilizeDeserialize
and add following two methods:
public class SerilizeDeserialize
{
// Serialize collection of any type to a byte stream
public static byte[] Serialize<T>(T obj)
{
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binSerializer = new BinaryFormatter();
binSerializer.Serialize(memStream, obj);
return memStream.ToArray();
}
}
// DSerialize collection of any type to a byte stream
public static T Deserialize<T>(byte[] serializedObj)
{
T obj = default(T);
using (MemoryStream memStream = new MemoryStream(serializedObj))
{
BinaryFormatter binSerializer = new BinaryFormatter();
obj = (T)binSerializer.Deserialize(memStream);
}
return obj;
}
}
How To use these method in your Class:
ArrayList arrayListMem = new ArrayList() { "One", "Two", "Three", "Four", "Five", "Six", "Seven" };
Console.WriteLine("Serializing to Memory : arrayListMem");
byte[] stream = SerilizeDeserialize.Serialize(arrayListMem);
ArrayList arrayListMemDes = new ArrayList();
arrayListMemDes = SerilizeDeserialize.Deserialize<ArrayList>(stream);
Console.WriteLine("DSerializing From Memory : arrayListMemDes");
foreach (var item in arrayListMemDes)
{
Console.WriteLine(item);
}
With CSS: table {float:left;}?
?
byte b = (byte)0xC8;
int v1 = b; // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)
Most of the time v2 is the way you really need.
The best and quick solution to the problem is first do this: View-> Show Symbol-> uncheck Show End of Line
This will solve problem for 90% of you and as in my case CR LF and its combinations still persist in the code. To fix this simply create a new tab using ctrl+n and copy whole file and paste in this new file. All CRLF gone, copy whole file again and go to original file delete whole code and paste the copied save and you rock!!!
Hope this helps.
I can tell this from out experience, having a current solution with 12 24 projects that includes API, MVC, Project Libraries (Core functionalities), WPF, UWP and Xamarin. It is worth reading this long post as I think it is the best way to do so. With the help of VS tools easily exportable and importable to sent to translation agencies or review by other people.
EDIT 02/2018: Still going strong, converting it to a .NET Standard library makes it possible to even use it across .NET Framework and NET Core. I added an extra section for converting it to JSON so for example angular can use it.
EDIT 2019: Going forward with Xamarin, this still works across all platforms. E.g. Xamarin.Forms advices to use resx files as well. (I did not develop an app in Xamarin.Forms yet, but the documentation, that is way to detailed to just get started, covers it: Xamarin.Forms Documentation). Just like converting it to JSON we can also convert it to a .xml file for Xamarin.Android.
EDIT 2019 (2): While upgrading to UWP from WPF, I encountered that in UWP they prefer to use another filetype .resw
, which is is in terms of content identical but the usage is different. I found a different way of doing this which, in my opinion, works better then the default solution.
EDIT 2020: Updated some suggestions for larger (modulair) projects that might require multiple language projects.
So, lets get to it.
Pro's
ResourceDirectories
.Thread.CurrentThread.CurrentCulture
Con's
Setup
Create language project in your solution, give it a name like MyProject.Language. Add a folder to it called Resources, and in that folder, create two Resources files (.resx). One called Resources.resx and another called Resources.en.resx (or .en-GB.resx for specific). In my implementation, I have NL (Dutch) language as the default language, so that goes in my first file, and English goes in my second file.
Setup should look like this:
The properties for Resources.resx must be:
Make sure that the custom tool namespace is set to your project namespace. Reason for this is that in WPF, you cannot reference to Resources
inside XAML.
And inside the resource file, set the access modifier to Public:
If you have such a large application (let's say different modules) you can consider creating multiple projects like above. In that case you could prefix your Keys and resource classes with the particular Module. Use the best language editor there is for Visual Studio to combine all files into a single overview.
Using in another project
Reference to your project: Right click on References -> Add Reference -> Prjects\Solutions.
Use namespace in a file: using MyProject.Language;
Use it like so in back-end:
string someText = Resources.orderGeneralError;
If there is something else called Resources, then just put in the entire namespace.
In MVC you can do however you like to set the language, but I used parameterized url's, which can be setup like so:
RouteConfig.cs Below the other mappings
routes.MapRoute(
name: "Locolized",
url: "{lang}/{controller}/{action}/{id}",
constraints: new { lang = @"(\w{2})|(\w{2}-\w{2})" }, // en or en-US
defaults: new { controller = "shop", action = "index", id = UrlParameter.Optional }
);
FilterConfig.cs (might need to be added, if so, add FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
to the Application_start()
method in Global.asax
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ErrorHandler.AiHandleErrorAttribute());
//filters.Add(new HandleErrorAttribute());
filters.Add(new LocalizationAttribute("nl-NL"), 0);
}
}
LocalizationAttribute
public class LocalizationAttribute : ActionFilterAttribute
{
private string _DefaultLanguage = "nl-NL";
private string[] allowedLanguages = { "nl", "en" };
public LocalizationAttribute(string defaultLanguage)
{
_DefaultLanguage = defaultLanguage;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string lang = (string) filterContext.RouteData.Values["lang"] ?? _DefaultLanguage;
LanguageHelper.SetLanguage(lang);
}
}
LanguageHelper just sets the Culture info.
//fixed number and date format for now, this can be improved.
public static void SetLanguage(LanguageEnum language)
{
string lang = "";
switch (language)
{
case LanguageEnum.NL:
lang = "nl-NL";
break;
case LanguageEnum.EN:
lang = "en-GB";
break;
case LanguageEnum.DE:
lang = "de-DE";
break;
}
try
{
NumberFormatInfo numberInfo = CultureInfo.CreateSpecificCulture("nl-NL").NumberFormat;
CultureInfo info = new CultureInfo(lang);
info.NumberFormat = numberInfo;
//later, we will if-else the language here
info.DateTimeFormat.DateSeparator = "/";
info.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
Thread.CurrentThread.CurrentUICulture = info;
Thread.CurrentThread.CurrentCulture = info;
}
catch (Exception)
{
}
}
Usage in .cshtml
@using MyProject.Language;
<h3>@Resources.w_home_header</h3>
or if you don't want to define usings then just fill in the entire namespace OR you can define the namespace under /Views/web.config:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
...
<add namespace="MyProject.Language" />
</namespaces>
</pages>
</system.web.webPages.razor>
This mvc implementation source tutorial: Awesome tutorial blog
Using in class libraries for models
Back-end using is the same, but just an example for using in attributes
using MyProject.Language;
namespace MyProject.Core.Models
{
public class RegisterViewModel
{
[Required(ErrorMessageResourceName = "accountEmailRequired", ErrorMessageResourceType = typeof(Resources))]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
}
}
If you have reshaper it will automatically check if the given resource name exists. If you prefer type safety you can use T4 templates to generate an enum
Ofcourse add a reference to your MyProject.Language namespace, we know how to use it in back-end.
In XAML, inside the header of a Window or UserControl, add a namespace reference called lang
like so:
<UserControl x:Class="Babywatcher.App.Windows.Views.LoginView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MyProject.App.Windows.Views"
xmlns:lang="clr-namespace:MyProject.Language;assembly=MyProject.Language" <!--this one-->
mc:Ignorable="d"
d:DesignHeight="210" d:DesignWidth="300">
Then, inside a label:
<Label x:Name="lblHeader" Content="{x:Static lang:Resources.w_home_header}" TextBlock.FontSize="20" HorizontalAlignment="Center"/>
Since it is strongly typed you are sure the resource string exists. You might need to recompile the project sometimes during setup, WPF is sometimes buggy with new namespaces.
One more thing for WPF, set the language inside the App.xaml.cs
. You can do your own implementation (choose during installation) or let the system decide.
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
SetLanguageDictionary();
}
private void SetLanguageDictionary()
{
switch (Thread.CurrentThread.CurrentCulture.ToString())
{
case "nl-NL":
MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo("nl-NL");
break;
case "en-GB":
MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo("en-GB");
break;
default://default english because there can be so many different system language, we rather fallback on english in this case.
MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo("en-GB");
break;
}
}
}
In UWP, Microsoft uses this solution, meaning you will need to create new resource files. Plus you can not re-use the text either because they want you to set the x:Uid
of your control in XAML to a key in your resources. And in your resources you have to do Example.Text
to fill a TextBlock
's text. I didn't like that solution at all because I want to re-use my resource files. Eventually I came up with the following solution. I just found this out today (2019-09-26) so I might come back with something else if it turns out this doesn't work as desired.
Add this to your project:
using Windows.UI.Xaml.Resources;
public class MyXamlResourceLoader : CustomXamlResourceLoader
{
protected override object GetResource(string resourceId, string objectType, string propertyName, string propertyType)
{
return MyProject.Language.Resources.ResourceManager.GetString(resourceId);
}
}
Add this to App.xaml.cs
in the constructor:
CustomXamlResourceLoader.Current = new MyXamlResourceLoader();
Where ever you want to in your app, use this to change the language:
ApplicationLanguages.PrimaryLanguageOverride = "nl";
Frame.Navigate(this.GetType());
The last line is needed to refresh the UI. While I am still working on this project I noticed that I needed to do this 2 times. I might end up with a language selection at the first time the user is starting. But since this will be distributed via Windows Store, the language is usually equal to the system language.
Then use in XAML:
<TextBlock Text="{CustomResource ExampleResourceKey}"></TextBlock>
Now days it is more common to have a framework like Angular in combination with components, so without cshtml. Translations are stored in json files, I am not going to cover how that works, I would just highly recommend ngx-translate instead of the angular multi-translation. So if you want to convert translations to a JSON file, it is pretty easy, I use a T4 template script that converts the Resources file to a json file. I recommend installing T4 editor to read the syntax and use it correctly because you need to do some modifications.
Only 1 thing to note: It is not possible to generate the data, copy it, clean the data and generate it for another language. So you have to copy below code as many times as languages you have and change the entry before '//choose language here'. Currently no time to fix this but probably will update later (if interested).
Path: MyProject.Language/T4/CreateLocalizationEN.tt
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Resources" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.ComponentModel.Design" #>
<#@ output extension=".json" #>
<#
var fileNameNl = "../Resources/Resources.resx";
var fileNameEn = "../Resources/Resources.en.resx";
var fileNameDe = "../Resources/Resources.de.resx";
var fileNameTr = "../Resources/Resources.tr.resx";
var fileResultName = "../T4/CreateLocalizationEN.json";//choose language here
var fileResultPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", fileResultName);
//var fileDestinationPath = "../../MyProject.Web/ClientApp/app/i18n/";
var fileNameDestNl = "nl.json";
var fileNameDestEn = "en.json";
var fileNameDestDe = "de.json";
var fileNameDestTr = "tr.json";
var pathBaseDestination = Directory.GetParent(Directory.GetParent(this.Host.ResolvePath("")).ToString()).ToString();
string[] fileNamesResx = new string[] {fileNameEn }; //choose language here
string[] fileNamesDest = new string[] {fileNameDestEn }; //choose language here
for(int x = 0; x < fileNamesResx.Length; x++)
{
var currentFileNameResx = fileNamesResx[x];
var currentFileNameDest = fileNamesDest[x];
var currentPathResx = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", currentFileNameResx);
var currentPathDest =pathBaseDestination + "/MyProject.Web/ClientApp/app/i18n/" + currentFileNameDest;
using(var reader = new ResXResourceReader(currentPathResx))
{
reader.UseResXDataNodes = true;
#>
{
<#
foreach(DictionaryEntry entry in reader)
{
var name = entry.Key;
var node = (ResXDataNode)entry.Value;
var value = node.GetValue((ITypeResolutionService) null);
if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\n", "");
if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\r", "");
#>
"<#=name#>": "<#=value#>",
<#
}
#>
"WEBSHOP_LASTELEMENT": "just ignore this, for testing purpose"
}
<#
}
File.Copy(fileResultPath, currentPathDest, true);
}
#>
If you have a modulair application and you followed my suggestion to create multiple language projects, then you will have to create a T4 file for each of them. Make sure the json files are logically defined, it doesn't have to be en.json
, it can also be example-en.json
. To combine multiple json files for using with ngx-translate, follow the instructions here
As explained above in the updates, I use the same method as I have done with Angular/JSON. But Android uses XML files, so I wrote a T4 file that generates those XML files.
Path: MyProject.Language/T4/CreateAppLocalizationEN.tt
#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Resources" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.ComponentModel.Design" #>
<#@ output extension=".xml" #>
<#
var fileName = "../Resources/Resources.en.resx";
var fileResultName = "../T4/CreateAppLocalizationEN.xml";
var fileResultRexPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", fileName);
var fileResultPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", fileResultName);
var fileNameDest = "strings.xml";
var pathBaseDestination = Directory.GetParent(Directory.GetParent(this.Host.ResolvePath("")).ToString()).ToString();
var currentPathDest =pathBaseDestination + "/MyProject.App.AndroidApp/Resources/values-en/" + fileNameDest;
using(var reader = new ResXResourceReader(fileResultRexPath))
{
reader.UseResXDataNodes = true;
#>
<resources>
<#
foreach(DictionaryEntry entry in reader)
{
var name = entry.Key;
//if(!name.ToString().Contains("WEBSHOP_") && !name.ToString().Contains("DASHBOARD_"))//only include keys with these prefixes, or the country ones.
//{
// if(name.ToString().Length != 2)
// {
// continue;
// }
//}
var node = (ResXDataNode)entry.Value;
var value = node.GetValue((ITypeResolutionService) null);
if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\n", "");
if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\r", "");
if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("&", "&");
if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("<<", "");
//if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("'", "\'");
#>
<string name="<#=name#>">"<#=value#>"</string>
<#
}
#>
<string name="WEBSHOP_LASTELEMENT">just ignore this</string>
<#
#>
</resources>
<#
File.Copy(fileResultPath, currentPathDest, true);
}
#>
Android works with values-xx
folders, so above is for English for in the values-en
folder. But you also have to generate a default which goes into the values
folder. Just copy above T4 template and change the folder in the above code.
There you go, you can now use one single resource file for all your projects. This makes it very easy exporting everything to an excl document and let someone translate it and import it again.
Special thanks to this amazing VS extension which works awesome with resx
files. Consider donating to him for his awesome work (I have nothing to do with that, I just love the extension).
Check this
UPDATE some_table SET some_field = REPLACE("Column Name/String", 'Search String', 'Replace String')
Eg with sample string:
UPDATE some_table SET some_field = REPLACE("this is test string", 'test', 'sample')
EG with Column/Field Name:
UPDATE some_table SET some_field = REPLACE(columnName, 'test', 'sample')
Perform the operation inside the scope itself.
<script>
angular.controller('MyCtrl', function($scope, $window) {
$scope.num1= 0;
$scope.num2= 1;
$scope.total = $scope.num1 + $scope.num2;
});
</script>
<input type="text" ng-model="num1">
<input type="text" ng-model="num2">
Total: {{total}}
var fs = require("fs");
var filename = "./index.html";
function start(resp) {
resp.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
resp.write(data);
resp.end();
});
}
You need to use delegates and protocols. Here is a site with an example http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html
What is the secret key does, you may have already known till now. It is basically HMAC SH256 (Secure Hash). The Secret is a symmetrical key.
Using the same key you can generate, & reverify, edit, etc.
For more secure, you can go with private, public key (asymmetric way). Private key to create token, public key to verify at client level.
Coming to secret key what to give You can give anything, "sudsif", "sdfn2173", any length
you can use online generator, or manually write
I prefer using openssl
C:\Users\xyz\Desktop>openssl rand -base64 12
65JymYzDDqqLW8Eg
generate, then encode with base 64
C:\Users\xyz\Desktop>openssl rand -out openssl-secret.txt -hex 20
The generated value is saved inside the file named "openssl-secret.txt"
generate, & store into a file.
One thing is giving 12 will generate, 12 characters only, but since it is base 64 encoded, it will be (4/3*n) ceiling value.
I recommend reading this article