(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:
GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \
git clone myuser@myGitRemoteServer:/my/remote/git_repo/path
This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).
If you want to get rid of it entirely, I've adjusted the code in the previous answers so it works on hover, active and focus too:
input:-webkit-autofill, input:-webkit-autofill:hover, input:-webkit-autofill:active, input:-webkit-autofill:focus {
-webkit-box-shadow: 0 0 0 1000px white inset;
}
This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.
in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #
Using Hamcrest:
assertThat( set1, both(everyItem(isIn(set2))).and(containsInAnyOrder(set1)));
This works also when the sets have different datatypes, and reports on the difference instead of just failing.
It appears that you do not see the need to incorporate some error tolerance. It would not be needed if all integers came entered as integers, however sometimes they come as a result of arithmetic operations that loose some precision. For example:
> 2/49*49
[1] 2
> check.integer(2/49*49)
[1] FALSE
> is.wholenumber(2/49*49)
[1] TRUE
Note that this is not R's weakness, all computer software have some limits of precision.
Add this function to your helper file and simply call.
function getRawQuery($sql){
$query = str_replace(array('?'), array('\'%s\''), $sql->toSql());
$query = vsprintf($query, $sql->getBindings());
return $query;
}
Output: "select * from user where status = '1' order by id desc limit 25 offset 0"
I am using Cent OS 6.6 with Apache and for me error log files are in
/usr/local/apache/log
There are libraries that do charset conversion in Javascript. But if you want something simple, this function does approximately what you want:
function stringToBytes(text) {
const length = text.length;
const result = new Uint8Array(length);
for (let i = 0; i < length; i++) {
const code = text.charCodeAt(i);
const byte = code > 255 ? 32 : code;
result[i] = byte;
}
return result;
}
If you want to convert the resulting byte array into a Blob, you would do something like this:
const originalString = 'ååå';
const bytes = stringToBytes(originalString);
const blob = new Blob([bytes.buffer], { type: 'text/plain; charset=ISO-8859-1' });
Now, keep in mind that some apps do accept UTF-8 encoding, but they can't guess the encoding unless you prepend a BOM character, as explained here.
You need to add your source files with git add
or the GUI equivalent so that Git will begin tracking them.
Use git status
to see what Git thinks about the files in any given directory.
Laravel has inbuilt support for multiple database systems, you need to provide connection details in config/database.php file
return [
'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
'mysqlOne' => [
'driver' => 'mysql',
'host' => env('DB_HOST_ONE', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE_ONE', 'forge'),
'username' => env('DB_USERNAME_ONE', 'forge'),
'password' => env('DB_PASSWORD_ONE', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
];
Once you have this you can create two base model class for each connection and define the connection name in those models
//BaseModel.php
protected $connection = 'mysql';
//BaseModelOne.php
protected $connection = 'mysqlOne';
You can extend these models to create more models for tables in each DB.
Building on the suggestion of using drawImage you could also combine this with scale function.
So before you draw the image scale the context to the zoom level you want:
ctx.scale(2, 2) // Doubles size of anything draw to canvas.
I've created a small example here http://jsfiddle.net/mBzVR/4/ that uses drawImage and scale to zoom in on mousedown and out on mouseup.
This issue come when I am using PHP as server side language and the work around was to generate base64 enconding of my image before sending the result to client
$path = 'E:/pat/rwanda.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
I think may give someone idea to create his own work around
Thanks
If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details. E.g.
String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}
RSS is the Resident Set Size and is used to show how much memory is allocated to that process and is in RAM. It does not include memory that is swapped out. It does include memory from shared libraries as long as the pages from those libraries are actually in memory. It does include all stack and heap memory.
VSZ is the Virtual Memory Size. It includes all memory that the process can access, including memory that is swapped out, memory that is allocated, but not used, and memory that is from shared libraries.
So if process A has a 500K binary and is linked to 2500K of shared libraries, has 200K of stack/heap allocations of which 100K is actually in memory (rest is swapped or unused), and it has only actually loaded 1000K of the shared libraries and 400K of its own binary then:
RSS: 400K + 1000K + 100K = 1500K
VSZ: 500K + 2500K + 200K = 3200K
Since part of the memory is shared, many processes may use it, so if you add up all of the RSS values you can easily end up with more space than your system has.
The memory that is allocated also may not be in RSS until it is actually used by the program. So if your program allocated a bunch of memory up front, then uses it over time, you could see RSS going up and VSZ staying the same.
There is also PSS (proportional set size). This is a newer measure which tracks the shared memory as a proportion used by the current process. So if there were two processes using the same shared library from before:
PSS: 400K + (1000K/2) + 100K = 400K + 500K + 100K = 1000K
Threads all share the same address space, so the RSS, VSZ and PSS for each thread is identical to all of the other threads in the process. Use ps or top to view this information in linux/unix.
There is way more to it than this, to learn more check the following references:
Also see:
There are a couple of ways that you can accomplish this. You can do the following:
<li>
@Html.ActionLink("Clients", "Index", "User", new { @class = "elements" }, null)
</li>
or this:
<li>
<a href="@Url.Action("Index", "Users")" class="elements">
<span>Clients</span>
</a>
</li>
Lately I do the following:
<a href="@Url.Action("Index", null, new { area = string.Empty, controller = "User" }, Request.Url.Scheme)">
<span>Clients</span>
</a>
The result would have http://localhost/10000
(or with whatever port you are using) to be appended to the URL structure like:
http://localhost:10000/Users
I hope this helps.
ok, everyone is making sense and I took all the pieces and put them here to help newbies like myself that need beginning to end explanation.
You make your big class that holds 2 classes, as per @Andrew's answer.
public class teamBoards{
public Boards Boards{get; set;}
public Team Team{get; set;}
}
Then in your controller you fill the 2 models. Sometimes you only need to fill one. Then in the return, you reference the big model and it will take the 2 inside with it to the View.
TeamBoards teamBoards = new TeamBoards();
teamBoards.Boards = (from b in db.Boards
where b.TeamId == id
select b).ToList();
teamBoards.Team = (from t in db.Teams
where t.TeamId == id
select t).FirstOrDefault();
return View(teamBoards);
At the top of the View
@model yourNamespace.Models.teamBoards
Then load your inputs or displays referencing the big Models contents:
@Html.EditorFor(m => Model.Board.yourField)
@Html.ValidationMessageFor(m => Model.Board.yourField, "", new { @class = "text-danger-yellow" })
@Html.EditorFor(m => Model.Team.yourField)
@Html.ValidationMessageFor(m => Model.Team.yourField, "", new { @class = "text-danger-yellow" })
And. . . .back at the ranch, when the Post comes in, reference the Big Class:
public ActionResult ContactNewspaper(teamBoards teamboards)
and make use of what the model(s) returned:
string yourVariable = teamboards.Team.yourField;
Probably have some DataAnnotation Validation stuff in the class and probably put if(ModelState.IsValid) at the top of the save/edit block. . .
You are missing <context:annotation-config />
from your spring context so the annotations are not being scanned!
I didn't go down the road of getting new DLL's. We had a bunch of existing projects that work perfectly fine and it was only my new project that was giving me headache so I decided to try something else.
My project was using an internally developed Internal.dll that depended on Oracle.DataAccess.dll v4.112.3.0
. For some reason, when publishing, Visual Studio always uploaded v4.121.0.0
, even though it wasn't explicitly specified in any of the config files. That's why I was getting an error.
So what I did was:
/bin
(just to be on the safe side)./bin
.myWebSite.csproj
, but it showed the wrong version: v4.121.0.0
instead of v4.112.3.0
.I manually changed the reference in myWebSite.csproj
, so it now read:
<Reference Include="Oracle.DataAccess, Version=4.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>bin\Oracle.DataAccess.dll</HintPath>
</Reference>
I didn't understand your question ... what do you mean by "when i set every one of my colour"? try this (edit: "#fffff" in original answer changed to "#ffffff"
yourView.setBackgroundColor(Color.parseColor("#ffffff"));
This.
$.each(
$('#some-element'),
function(i, item){
item.addEventListener('DOMNodeRemovedFromDocument',
function(e){ console.log('I has been removed'); console.log(e);
})
})
Set this in HTML:
<div class="modal-body " [formGroup]="Form">
<div class="">
<mat-checkbox formControlName="a" [disabled]="true"> Display 1</mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="b" [disabled]="true"> Display 2 </mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="c" [disabled]="true"> Display 3 </mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="d" [disabled]="true"> Display 4</mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="e" [disabled]="true"> Display 5 </mat-checkbox>
</div>
</div>
Changes in Ts file
this.Form = this.formBuilder.group({
a: false,
b: false,
c: false,
d: false,
e: false,
});
Conditionvalidation in Ur Business logic
if(true){
this.Form.patch(a: true);
}
Gradle (build.gradle):
implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")
Entity (User.class):
LocalDate dateOfBirth;
Code:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
User user = mapper.readValue(json, User.class);
Maybe in your data source add a column which does a sumif over all rows.
Not sure what your data looks like but something like =(sumif([column holding pivot row heads),[current row head value in row], probability column)>.2).
This will give you a True when the pivot table will show >20%.
Then add a filter on your pivot table on this column for TRUE values
You can use SublimeREPL (you need to have Package Control installed first).
It's always better to use the iterator instead of indexing. This is because iterator is most likely optimzied for the List implementation while indexed (calling get) might not be. For example LinkedList is a List but indexing through its elements will be slower than iterating using the iterator.
For debug/release flags, see the CMAKE_BUILD_TYPE
variable (you pass it as cmake -DCMAKE_BUILD_TYPE=value
). It takes values like Release
, Debug
, etc.
https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/Useful-Variables#compilers-and-tools
cmake uses the extension to choose the compiler, so just name your files .c.
You can override this with various settings:
For example:
set_source_files_properties(yourfile.c LANGUAGE CXX)
Would compile .c files with g++. The link above also shows how to select a specific compiler for C/C++.
How to make the HTML link activated by clicking on the <li> ?
By making your link as big as your li: just move the instruction
display: block;
from li to a and you are done.
That is:
#menu li
{
/* no more display:block; on list item */
list-style: none;
background: #e8eef4 url(arrow.gif) 2% 50% no-repeat;
border: 1px solid #b2b2b2;
padding: 0;
margin-top: 5px;
}
#menu li a
{
display:block; /* moved to link */
font-weight: bold;
text-decoration: none;
line-height: 2.8em;
padding-right:.5em;
color: #696969;
}
Side note: you can remove "ul" from your two selectors: #menu is a sufficient indication except if you need to give weight to these two rules in order to override other instructions.
Short Answer:
Long Answer:
What is the purpose of a URL?
If pointing to an address is the answer, then a shortened URL is also doing a good job. If we don't make it easy to read and maintain, it won't help developers and maintainers alike. They represent an entity on the server, so they must be named logically.
Google recommends using hyphens
Consider using punctuation in your URLs. The URL http://www.example.com/green-dress.html is much more useful to us than http://www.example.com/greendress.html. We recommend that you use hyphens (-) instead of underscores (_) in your URLs.
Coming from a programming background, camelCase is a popular choice for naming joint words.
But RFC 3986 defines URLs as case-sensitive for different parts of the URL. Since URLs are case sensitive, keeping it low-key (lower cased) is always safe and considered a good standard. Now that takes a camel case out of the window.
Source: https://metamug.com/article/rest-api-naming-best-practices.html#word-delimiters
If you are getting a timeout while on the table designer, change the "Transaction time-out after" value under Tools --> Options --> Designers --> Table and Database Designers
This will get rid of this message: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."
If you use Less you can directly use the following mixin:
.@{fa-css-prefix}-rotate-90 { .fa-icon-rotate(90deg, 1); }
Follow the below steps:
Select body > form-data and do same as shown in the image.
Now in your Django view.py
def post(self, request, *args, **kwargs): image = request.FILES["image"] data = json.loads(request.data['data']) ... return Response(...)
My way on Windows 8
Add a directory with ssh-keygen to the system PATH variable, usually C:\Program Files (x86)\Git\bin
Open CMD, go to C:\Users\Me\
Generate SSH key ssh-keygen -t rsa
Enter file in which to save the key (//.ssh/id_rsa): .ssh/id_rsa (change a default incorrect path to .ssh/somegoodname_rsa)
Add the key to Heroku heroku keys:add
Select a created key from a list
Go to your app directory, write some beautiful code
Init a git repo git init
git add .
git commit -m 'chore(release): v0.0.1
Create Heroku application heroku create
Deploy your app git push heroku master
Open your app heroku open
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
Short answer: You can't.
@Backslash17: Looking through the article and the following link with installation instructions, all the company got working is to launch a self compiled executable on the emulator, bypassing the android framework. Once you have the emulator you can telnet in and have a linux shell. Running a linux program there is trivial of course. But that's not working for phones without jailbreak(aka root access) and not deliverable on the market.
Unless Google opens other opportunities or someone writes a custom compiler that compiles Language X into Dalvik bytecode (Dalvik is the VM that runs Android programs) you won't be able to write native code.
using node-fs-extra (async await)
const readJsonFile = async () => {
try {
const myJsonObject = await fs.readJson('./my_json_file.json');
console.log(myJsonObject);
} catch (err) {
console.error(err)
}
}
readJsonFile() // prints your json object
I think this is the best and easy way:
$lista = @()
$lista += ('{"name": "Diego" }' | ConvertFrom-Json)
$lista += ('{"name": "Monica" }' | ConvertFrom-Json)
$lista += ('{"name": "Celia" }' | ConvertFrom-Json)
$lista += ('{"name": "Quin" }' | ConvertFrom-Json)
if ("Diego" -in $lista.name) {
Write-Host "is in the list"
return $true
}
else {
Write-Host "not in the list"
return $false
}
The lower the loss, the better a model (unless the model has over-fitted to the training data). The loss is calculated on training and validation and its interperation is how well the model is doing for these two sets. Unlike accuracy, loss is not a percentage. It is a summation of the errors made for each example in training or validation sets.
In the case of neural networks, the loss is usually negative log-likelihood and residual sum of squares for classification and regression respectively. Then naturally, the main objective in a learning model is to reduce (minimize) the loss function's value with respect to the model's parameters by changing the weight vector values through different optimization methods, such as backpropagation in neural networks.
Loss value implies how well or poorly a certain model behaves after each iteration of optimization. Ideally, one would expect the reduction of loss after each, or several, iteration(s).
The accuracy of a model is usually determined after the model parameters are learned and fixed and no learning is taking place. Then the test samples are fed to the model and the number of mistakes (zero-one loss) the model makes are recorded, after comparison to the true targets. Then the percentage of misclassification is calculated.
For example, if the number of test samples is 1000 and model classifies 952 of those correctly, then the model's accuracy is 95.2%.
There are also some subtleties while reducing the loss value. For instance, you may run into the problem of over-fitting in which the model "memorizes" the training examples and becomes kind of ineffective for the test set. Over-fitting also occurs in cases where you do not employ a regularization, you have a very complex model (the number of free parameters W
is large) or the number of data points N
is very low.
The reason why you don't see such practice is quite subjective and cannot have a definite answer, because I have seen many of the code which uses your mentioned way rather than iterator
style code.
Following can be reasons of people not considering vector.size()
way of looping:
size()
every time in the loop
condition. However either it's a non-issue or it can be trivially
fixedstd::for_each()
over the for
loop itselfstd::vector
to other one (e.g.
map
, list
) will also demand the change of the looping mechanism,
because not every container support size()
style of loopingC++11 provides a good facility to move through the containers. That is called "range based for loop" (or "enhanced for loop" in Java).
With little code you can traverse through the full (mandatory!) std::vector
:
vector<int> vi;
...
for(int i : vi)
cout << "i = " << i << endl;
For Kotlin :
fun getFolderName() {
val uri: Uri
val cursor: Cursor?
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(MediaStore.Audio.AudioColumns.DATA)
cursor = requireActivity().contentResolver.query(uri, projection, null, null, null)
if (cursor != null) {
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA)
}
while (cursor!!.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data)
val fileName: String = File(absolutePathOfImage).parentFile.name
}
}
Currently there is another approach possible if classes are used in code.
With support of class fields it's possible to make it next way:
class someView {
onSomeInputKeyUp = (event) => {
console.log(this); // this refers to correct value
// ....
someInitMethod() {
//...
someInput.addEventListener('input', this.onSomeInputKeyUp)
For sure under the hood it's all old good arrow function that bind context but in this form it looks much more clear that explicit binding.
Since it's Stage 3 Proposal you will need babel and appropriate babel plugin to process it as for now(08/2018).
Magic:
$ git svn clone http://svn/repo/here/trunk
Git and SVN operate very differently. You need to learn Git, and if you want to track changes from SVN upstream, you need to learn git-svn
. The git-svn
main page has a good examples section:
$ git svn --help
CHAR is a fixed length field; VARCHAR is a variable length field. If you are storing strings with a wildly variable length such as names, then use a VARCHAR, if the length is always the same, then use a CHAR because it is slightly more size-efficient, and also slightly faster.
If you want to apply to all columns you can use:
df.apply(pd.value_counts)
This will apply a column based aggregation function (in this case value_counts) to each of the columns.
While searching for the best method to sum an array, I wrote a performance test.
In Chrome, "reduce" seems to be vastly superior
I hope this helps
// Performance test, sum of an array
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var result = 0;
// Eval
console.time("eval");
for(var i = 0; i < 10000; i++) eval("result = (" + array.join("+") + ")");
console.timeEnd("eval");
// Loop
console.time("loop");
for(var i = 0; i < 10000; i++){
result = 0;
for(var j = 0; j < array.length; j++){
result += parseInt(array[j]);
}
}
console.timeEnd("loop");
// Reduce
console.time("reduce");
for(var i = 0; i < 10000; i++) result = array.reduce(function(pv, cv) { return pv + parseInt(cv); }, 0);
console.timeEnd("reduce");
// While
console.time("while");
for(var i = 0; i < 10000; i++){
j = array.length;
result = 0;
while(j--) result += array[i];
}
console.timeEnd("while");
eval: 5233.000ms
loop: 255.000ms
reduce: 70.000ms
while: 214.000ms
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
Dot notation is always preferable. If you are using some "smarter" IDE or text editor, it will show undefined names from that object. Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.
select replace(convert(VARCHAR,getdate(),103),'/','')
select right(convert(VARCHAR,getdate(),112),2) +
substring(convert(VARCHAR,getdate(),112),5,2) +
left(convert(VARCHAR,getdate(),112),4)
If you assume that there can be duplicate values the only way to do this is to put the values in lists, sort them and compare the lists viz:
List<String> values1 = new ArrayList<String>(map1.values());
List<String> values2 = new ArrayList<String>(map2.values());
Collections.sort(values1);
Collections.sort(values2);
boolean mapsHaveEqualValues = values1.equals(values2);
If values cannot contain duplicate values then you can either do the above without the sort using sets.
The minimum width that your screen can display is 1 pixel. So its impossible to display less then 1px. 1 pixels can only have 1 color and cannot be split up.
simple:
Tags are expected to always point at the same version of a project, while heads are expected to advance as development progresses.
I was facing following error with code (nodejs 0.10.13), provided by ampersand:
origin is not allowed by access-control-allow-origin
Issue was resolved changing
response.writeHead(200, {"Content-Type": "text/plain"});
to
response.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin' : '*'});
Set the KeyPreview attribute on your form to True, then use the KeyPress event at your form level to detect the Enter key. On detection call whatever code you would have for the "submit" button.
In Ruby 2.1.3 things have changed:
> endDate = Date.new(2014, 1, 2)
=> #<Date: 2014-01-02 ((2456660j,0s,0n),+0s,2299161j)>
> beginDate = Date.new(2014, 1, 1)
=> #<Date: 2014-01-01 ((2456659j,0s,0n),+0s,2299161j)>
> days = endDate - beginDate
=> (1/1)
> days.class
=> Rational
> days.to_i
=> 1
Using the utility I describe here, you can have a more control over the string representation you get for your array.
String[] s = { "hello", "world" };
RichIterable<String> r = RichIterable.from(s);
r.mkString(); // gives "hello, world"
r.mkString(" | "); // gives "hello | world"
r.mkString("< ", ", ", " >"); // gives "< hello, world >"
The following links will help you:
In Client side design page you can try this: {0:G}
OR
You can convert that datetime format inside the query itself from the database:
The first thing i noticed is that you have a semi colon just after your closing bracket for your if statement );
You should also try and clean up your if statement by declaring a variable for the answer separately.
function answers() {
var select = document.getElementById("mySelect");
var answer = select.options[select.selectedIndex].value;
if(answer == "To measure time"){
alert("Thats correct");
}
}
virtualenv --python=/usr/local/bin/python3 <VIRTUAL ENV NAME>
this will add python3
path for your virtual enviroment.
XML code:
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false" />
</android.support.v4.widget.NestedScrollView>
in java code :
recycleView = (RecyclerView) findViewById(R.id.recycleView);
recycleView.setNestedScrollingEnabled(false);
XCODE 9 AND ABOVE
#if DEVELOP
//
#elseif PRODCTN
//
#else
//
#endif
const tifOptions = [];
for (const [key, value] of Object.entries(tifs)) {
tifOptions.push(<option value={key} key={key}>{value}</option>);
}
return (
<select id="tif" name="tif" onChange={this.handleChange}>
{ tifOptions }
</select>
)
This error message seems to come up in various situations.
In my case, on top of my application's Web.Config file I had an extra Web.Config file in the root folder (C:\Inetpub\www.root). Probably left there after some testing, I had forgotten all about it, and couldn't figure out what the problem was.
Removing it solved the problem for me.
I use Jestr with reasonable results.
I took Eugen Rieck's answer and worked with it. My code adds the following:
ps ax
includes grep, so I excluded it with grep -Eiv 'grep'
I've created a file, named it killserver
, here it goes:
#!/bin/bash
PROCESS_TO_KILL=bin/node
PROCESS_LIST=`ps ax | grep -Ei ${PROCESS_TO_KILL} | grep -Eiv 'grep' | awk ' { print $1;}'`
KILLED=
for KILLPID in $PROCESS_LIST; do
if [ ! -z $KILLPID ];then
kill -9 $KILLPID
echo "Killed PID ${KILLPID}"
KILLED=yes
fi
done
if [ -z $KILLED ];then
echo "Didn't kill anything"
fi
Results
? myapp git:(master) bash killserver
Killed PID 3358
Killed PID 3382
Killed
? myapp git:(master) bash killserver
Didn't kill anything
There is no ForEach extension for IEnumerable
; only for List<T>
. So you could do
items.ToList().ForEach(i => i.DoStuff());
Alternatively, write your own ForEach extension method:
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach(T item in enumeration)
{
action(item);
}
}
Both array_push
and the method you described will work.
$cart = array();
$cart[] = 13;
$cart[] = 14;
// etc
//Above is correct. but below one is for further understanding
$cart = array();
for($i=0;$i<=5;$i++){
$cart[] = $i;
}
echo "<pre>";
print_r($cart);
echo "</pre>";
Is the same as:
<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);
// Or
$cart = array();
array_push($cart, 13, 14);
?>
I had the same issue. For me it helped to remove the .vs directory in the project folder.
The method you want is BigInteger#valueOf(long val).
E.g.,
BigInteger bi = BigInteger.valueOf(myInteger.intValue());
Making a String first is unnecessary and undesired.
I had the same problem with one of my apps, which is how I ended up finding this. In my case, I uploaded two of my apps at the same time, using Xcode 7.1. One of the apps passed through processing within an hour. The other one was still in processing almost 24 hours later. To get past this issue, I created a new archive with an incremented build number, and uploaded it using the application loader. I did not turn off bitcode. The version that I uploaded using the application loader took less than 20 minutes to get through processing, and I've been able to submit my app for review. The version I submitted prior to this is still stuck in processing.
At least in the case of my app, using application loader appears to have solved the issue.
Angular 8 HttpClient Error Handling Service Example
api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Student } from '../model/student';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiService {
// API path
base_path = 'http://localhost:3000/students';
constructor(private http: HttpClient) { }
// Http Options
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
// Handle API errors
handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
// Create a new item
createItem(item): Observable<Student> {
return this.http
.post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
.pipe(
retry(2),
catchError(this.handleError)
)
}
........
........
}
The following worked for me:
Registry Editor
(press windows key, type regedit
and hit Enter
) .HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
and clear the values.HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
.Looking for a super simple solution:
SUBSTRING([Phone], CHARINDEX('(', [Phone], 1)+1, 3)
+ SUBSTRING([Phone], CHARINDEX(')', [Phone], 1)+1, 3)
+ SUBSTRING([Phone], CHARINDEX('-', [Phone], 1)+1, 4) AS Phone
You should use setStroke
to set a stroke of the Graphics2D
object.
The example at http://www.java2s.com gives you some code examples.
The following code produces the image below:
import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;
public class FrameTest {
public static void main(String[] args) {
JFrame jf = new JFrame("Demo");
Container cp = jf.getContentPane();
cp.add(new JComponent() {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));
g2.draw(new Line2D.Float(30, 20, 80, 90));
}
});
jf.setSize(300, 200);
jf.setVisible(true);
}
}
(Note that the setStroke
method is not available in the Graphics
object. You have to cast it to a Graphics2D
object.)
This post has been rewritten as an article here.
you have to do like this in your project level gradle file
allprojects {
repositories {
jcenter()
maven { url "http://dl.appnext.com/" }
maven { url "https://maven.google.com" }
}
}
This is a kotlin solution. Put this helper method in some kotlin file-
fun EditText.setupClearButtonWithAction() {
addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable?) {
val clearIcon = if (editable?.isNotEmpty() == true) R.drawable.ic_clear else 0
setCompoundDrawablesWithIntrinsicBounds(0, 0, clearIcon, 0)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
})
setOnTouchListener(View.OnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_UP) {
if (event.rawX >= (this.right - this.compoundPaddingRight)) {
this.setText("")
return@OnTouchListener true
}
}
return@OnTouchListener false
})
}
And then use it as following in the onCreate
method and you should be good to go-
yourEditText.setupClearButtonWithAction()
BTW, you have to add R.drawable.ic_clear
or the clear icon at first. This one is from google- https://material.io/tools/icons/?icon=clear&style=baseline
import yaml
data = dict(
A = 'a',
B = dict(
C = 'c',
D = 'd',
E = 'e',
)
)
with open('data.yml', 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
The default_flow_style=False
parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:
A: a
B: {C: c, D: d, E: e}
int index= datagridview.rows.add();
datagridview.rows[index].cells[1].value=1;
datagridview.rows[index].cells[2].value="a";
datagridview.rows[index].cells[3].value="b";
hope this help! :)
Ok, this might be a little after the fact, but .promise() should also achieve what you're after.
An example from a project i'm working on:
$( '.panel' )
.fadeOut( 'slow')
.promise()
.done( function() {
$( '#' + target_panel ).fadeIn( 'slow', function() {});
});
:)
OK, I found some time and followed the suggestion by Teemu and I was able to get exactly what I wanted.
So here is the final code for anyone that might be interested. For clarification, this code gets all checked checkboxes of a certain ID, outputs them in an array, named here checkbx
, and then copies their unique name to the clipboard.
JavaScript function:
function getSelectedCheckboxes(chkboxName) {
var checkbx = [];
var chkboxes = document.getElementsByName(chkboxName);
var nr_chkboxes = chkboxes.length;
for(var i=0; i<nr_chkboxes; i++) {
if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
}
checkbx.toString();
// Create a dummy input to copy the string array inside it
var dummy = document.createElement("input");
// Add it to the document
document.body.appendChild(dummy);
// Set its ID
dummy.setAttribute("id", "dummy_id");
// Output the array into it
document.getElementById("dummy_id").value=checkbx;
// Select it
dummy.select();
// Copy its contents
document.execCommand("copy");
// Remove it as its not needed anymore
document.body.removeChild(dummy);
}
And its HTML call:
<button id="btn_test" type="button" onclick="getSelectedCheckboxes('ID_of_chkbxs_selected')">Copy</button>
Some great answers above, using that info here is what I did today to solve the same issue:
$to_array = explode(',', $to);
foreach($to_array as $address)
{
$mail->addAddress($address, 'Web Enquiry');
}
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
In addition to standard net/http package, you can consider using my GoRequest which wraps around net/http and make your life easier without thinking too much about json or struct. But you can also mix and match both of them in one request! (you can see more details about it in gorequest github page)
So, in the end your code will become like follow:
func main() {
url := "http://restapi3.apiary.io/notes"
fmt.Println("URL:>", url)
request := gorequest.New()
titleList := []string{"title1", "title2", "title3"}
for _, title := range titleList {
resp, body, errs := request.Post(url).
Set("X-Custom-Header", "myvalue").
Send(`{"title":"` + title + `"}`).
End()
if errs != nil {
fmt.Println(errs)
os.Exit(1)
}
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
fmt.Println("response Body:", body)
}
}
This depends on how you want to achieve. I made this library because I have the same problem with you and I want code that is shorter, easy to use with json, and more maintainable in my codebase and production system.
This is an odd solution, but it worked for me.
I wanted to uninstall Visual Studio 2015 and do a clean install afterwards, but when I tried to remove it through the Control Panel, it was giving me a generic error.
I fixed it by deleting the Visual Studio 2015 folder in Program Files (x86). After that, the Control Panel uninstall worked fine.
You could use the following regex code to validate 2 names separeted by a space with the following regex code:
^[A-Za-zÀ-ú]+ [A-Za-zÀ-ú]+$
[[:lower:]] = [a-zà-ú]
[[:upper:]] =[A-ZÀ-Ú]
[[:alpha:]] = [A-Za-zÀ-ú]
[[:alnum:]] = [A-Za-zÀ-ú0-9]
Use a ssh key.
Look at ssh-keygen
and ssh-copy-id
.
After that you can use an rsync
this way :
rsync -a --stats --progress --delete /home/path server:path
if You use Laravel version 5.2 Review this: https://laravel.com/docs/5.2/requests#accessing-the-request
use Illuminate\Http\Request;//Access able for All requests
...
class myController extends Controller{
public function myfunction(Request $request){
$name = $request->input('username');
}
}
I know this is a little old but for the sake of folks like myself from google who didn't find a complete answer here. Here are some extracts from my app which put the arrows inside a custom listview....
Location loc; //Will hold lastknown location
Location wptLoc = new Location(""); // Waypoint location
float dist = -1;
float bearing = 0;
float heading = 0;
float arrow_rotation = 0;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc == null) { //No recent GPS fix
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setSpeedRequired(false);
loc = lm.getLastKnownLocation(lm.getBestProvider(criteria, true));
}
if(loc != null) {
wptLoc.setLongitude(cursor.getFloat(2)); //Cursor is from SimpleCursorAdapter
wptLoc.setLatitude(cursor.getFloat(3));
dist = loc.distanceTo(wptLoc);
bearing = loc.bearingTo(wptLoc); // -180 to 180
heading = loc.getBearing(); // 0 to 360
// *** Code to calculate where the arrow should point ***
arrow_rotation = (360+((bearing + 360) % 360)-heading) % 360;
}
I willing to bet it could be simplified but it works! LastKnownLocation was used since this code was from new SimpleCursorAdapter.ViewBinder()
onLocationChanged contains a call to notifyDataSetChanged();
code also from new SimpleCursorAdapter.ViewBinder() to set image rotation and listrow colours (only applied in a single columnIndex mind you)...
LinearLayout ll = ((LinearLayout)view.getParent());
ll.setBackgroundColor(bc);
int childcount = ll.getChildCount();
for (int i=0; i < childcount; i++){
View v = ll.getChildAt(i);
if(v instanceof TextView) ((TextView)v).setTextColor(fc);
if(v instanceof ImageView) {
ImageView img = (ImageView)v;
img.setImageResource(R.drawable.ic_arrow);
Matrix matrix = new Matrix();
img.setScaleType(ScaleType.MATRIX);
matrix.postRotate(arrow_rotation, img.getWidth()/2, img.getHeight()/2);
img.setImageMatrix(matrix);
}
In case you're wondering I did away with the magnetic sensor dramas, wasn't worth the hassle in my case. I hope somebody finds this as useful as I usually do when google brings me to stackoverflow!
You can attempt to push the cookie val to another domain using an image tag.
Your mileage may vary when trying to do this because some browsers require you to have a proper P3P Policy on the WebApp2 domain or the browser will reject the cookie.
If you look at plus.google.com p3p policy you will see that their policy is:
CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
that is the policy they use for their +1 buttons to these cross domain requests.
Another warning is that if you are on https make sure that the image tag is pointing to an https address also otherwise the cookies will not set.
One more version... (I think this one is pretty good)
static float NextFloat(Random random)
{
(float)(float.MaxValue * 2.0 * (rand.NextDouble()-0.5));
}
//inline version
float myVal = (float)(float.MaxValue * 2.0 * (rand.NextDouble()-0.5));
I think this...
And One more version...(not as good but posting anyway)
static float NextFloat(Random random)
{
return float.MaxValue * ((rand.Next() / 1073741824.0f) - 1.0f);
}
//inline version
float myVal = (float.MaxValue * ((rand.Next() / 1073741824.0f) - 1.0f));
I think this...
Testing of most of the functions on this page: (i7, release, without debug, 2^28 loops)
Sunsetquest1: min: 3.402823E+38 max: -3.402823E+38 time: 3096ms
SimonMourier: min: 3.402823E+38 max: -3.402819E+38 time: 14473ms
AnthonyPegram:min: 3.402823E+38 max: -3.402823E+38 time: 3191ms
JonSkeet: min: 3.402823E+38 max: -3.402823E+38 time: 3186ms
Sixlettervar: min: 1.701405E+38 max: -1.701410E+38 time: 19653ms
Sunsetquest2: min: 3.402823E+38 max: -3.402823E+38 time: 2930ms
From the Developer Guide:
android:id="@+id/my_button"
The at-symbol (@
) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+
) means that this is a new resource name that must be created and added to our resources (in the R.java
file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android
package namespace, like so:
android:id="@android:id/empty"
If your user account has spaces in it and you have tried all the above but none worked,
I recommended you create a new windows user account and give it an administrative privilege, not standard.
Log out of your old account and log into this new account and try installing again. It worked well.
If you can't use "viewWillDisappear" or similar method, try to subclass UINavigationController. This is the header class:
#import <Foundation/Foundation.h>
@class MyViewController;
@interface CCNavigationController : UINavigationController
@property (nonatomic, strong) MyViewController *viewController;
@end
Implementation class:
#import "CCNavigationController.h"
#import "MyViewController.h"
@implementation CCNavigationController {
}
- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
@"This is the moment for you to do whatever you want"
[self.viewController doCustomMethod];
return [super popViewControllerAnimated:animated];
}
@end
In the other hand, you need to link this viewController to your custom NavigationController, so, in your viewDidLoad method for your regular viewController do this:
@implementation MyViewController {
- (void)viewDidLoad
{
[super viewDidLoad];
((CCNavigationController*)self.navigationController).viewController = self;
}
}
<meta http-equiv="refresh" content="600; url=index.php">
600 is the amount of seconds between refresh cycles.
You should autowire interface AbstractManager
instead of class MailManager
. If you have different implemetations of AbstractManager
you can write @Component("mailService")
and then @Autowired @Qualifier("mailService")
combination to autowire specific class.
This is due to the fact that Spring creates and uses proxy objects based on the interfaces.
UPDATE: Please see Dylan's or d.c's anwer for a little easier (and more stable) solution, which does not rely on Chrome beeing installed in LocalAppData
!
Even if I agree with Daniel Hilgarth to open a new tab in chrome you just need to execute chrome.exe with your URL as the argument:
Process.Start(@"%AppData%\..\Local\Google\Chrome\Application\chrome.exe",
"http:\\www.YourUrl.com");
With these two steps we can check if it LL(1) or not. Both of them have to be satisfied.
1.If we have the production:A->a1|a2|a3|a4|.....|an. Then,First(a(i)) intersection First(a(j)) must be phi(empty set)[a(i)-a subscript i.]
2.For every non terminal 'A',if First(A) contains epsilon Then First(A) intersection Follow(A) must be phi(empty set).
Nothing - Google says it clearly that the application is identified by the keys used to sign it. Consequently if you've lost the keys, you need to create a new application.
You should consider creating a timestamp from that date witk mktime()
eg:
$date = explode('/', $_POST['date']);
$time = mktime(0,0,0,$date[0],$date[1],$date[2]);
$mysqldate = date( 'Y-m-d H:i:s', $time );
Or also you can do something like this.
<div style="background=#aeaeae; float: right">
</div>
We can add any CSS inside the style attribute of HTML tags.
The base dn is dc=example,dc=com
.
I don't know about openca, but I will try this answer since you got very little traffic so far.
A base dn is the point from where a server will search for users. So I would try to simply use admin
as a login name.
If openca behaves like most ldap aware applications, this is what is going to happen :
admin
will be done by the server starting at the base dn (dc=example,dc=com
).cn=admin,dc=example,dc=com
) will be used to bind with the supplied password.Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :
dn
your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com
.objectClass
for your admin
user. It will be either inetOrgPerson
or user
. There will be others like top
, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson)
. Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user))
. Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.
You could just iterate the result and count them. You don't say what language or client library you are using, but the API does provide a mysql_num_rows function which can tell you the number of rows in a result.
This is exposed in PHP, for example, as the mysqli_num_rows function. As you've edited the question to mention you're using PHP, here's a simple example using mysqli functions:
$link = mysqli_connect("localhost", "user", "password", "database");
$result = mysqli_query($link, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
Just use COUNT(*) - see Counting Rows in the MySQL manual. For example:
SELECT COUNT(*) FROM foo WHERE bar= 'value';
If you'd used a LIMIT clause but want to know how many rows you'd get without it, use SQL_CALC_FOUND_ROWS in your query, followed by SELECT FOUND_ROWS();
SELECT SQL_CALC_FOUND_ROWS * FROM foo
WHERE bar="value"
LIMIT 10;
SELECT FOUND_ROWS();
For very large tables, this isn't going to be particularly efficient, and you're better off running a simpler query to obtain a count and caching it before running your queries to get pages of data.
You can create a large array and then copy it to a new array using System.arrayCopy
int contentLength = 100000000;
byte[] byteArray = new byte[contentLength];
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
while ((bytesRead = inputStream.read()) != -1)
{
byteArray[count++] = (byte)bytesRead;
}
byte[] destArray = new byte[count];
System.arraycopy(byteArray, 0, destArray , 0, count);
destArray will contain the information you want
first import os module in your app than with use from getpid function get pid's app and save in a file.for example :
import os
pid = os.getpid()
op = open("/var/us.pid","w")
op.write("%s" % pid)
op.close()
and create a bash file in /etc/init.d path: /etc/init.d/servername
PATHAPP="/etc/bin/userscript.py &"
PIDAPP="/var/us.pid"
case $1 in
start)
echo "starting"
$(python $PATHAPP)
;;
stop)
echo "stoping"
PID=$(cat $PIDAPP)
kill $PID
;;
esac
now , u can start and stop ur app with down command:
service servername stop service servername start
or
/etc/init.d/servername stop /etc/init.d/servername start
Even though the ID selector is the simplest, you can also use the name selector as below:
$('[name='submitted[first_name]']').removeAttr('required');
For more see: https://api.jquery.com/attribute-equals-selector/
Java 8 now supports BASE64 Encoding and Decoding. You can use the following classes:
java.util.Base64
, java.util.Base64.Encoder
and java.util.Base64.Decoder
.
Example usage:
// encode with padding
String encoded = Base64.getEncoder().encodeToString(someByteArray);
// encode without padding
String encoded = Base64.getEncoder().withoutPadding().encodeToString(someByteArray);
// decode a String
byte [] barr = Base64.getDecoder().decode(encoded);
I found its work by restarting my phone :)
Assuming that you have the power to make schema changes the only acceptable answer to this question IMO is to change the base data type to something more appropriate (e.g. date
if SQL Server 2008).
Storing dates as mm/dd/yyyy
strings is space inefficient, difficult to validate correctly and makes sorting and date calculations needlessly painful.
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
>>> s = 'abcd'
>>> len(s)
4
I've written the tests that compare using regular expressions (as per other answers) against not using regular expressions. Tests done on a quad core OSX10.8 machine running Java 1.6
Interestingly using regular expressions turns out to be about 5-10 times slower than manually iterating over a string. Furthermore the isAlphanumeric2()
function is marginally faster than isAlphanumeric()
. One supports the case where extended Unicode numbers are allowed, and the other is for when only standard ASCII numbers are allowed.
public class QuickTest extends TestCase {
private final int reps = 1000000;
public void testRegexp() {
for(int i = 0; i < reps; i++)
("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
}
public void testIsAlphanumeric() {
for(int i = 0; i < reps; i++)
isAlphanumeric("ab4r3rgf"+i);
}
public void testIsAlphanumeric2() {
for(int i = 0; i < reps; i++)
isAlphanumeric2("ab4r3rgf"+i);
}
public boolean isAlphanumeric(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (!Character.isLetterOrDigit(c))
return false;
}
return true;
}
public boolean isAlphanumeric2(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
return false;
}
return true;
}
}
Or even just
git version
Results in something like
git version 1.8.3.msysgit.0
If you need to know the installed path under Windows without starting the python interpreter, have a look in the Windows registry.
Each installed Python version will have a registry key in either:
HKLM\SOFTWARE\Python\PythonCore\versionnumber\InstallPath
HKCU\SOFTWARE\Python\PythonCore\versionnumber\InstallPath
In 64-bit Windows, it will be under the Wow6432Node
key:
HKLM\SOFTWARE\Wow6432Node\Python\PythonCore\versionnumber\InstallPath
I've opened a similar question in the Doctrine user mailing list and got a really simple answer;
consider the many to many relation as an entity itself, and then you realize you have 3 objects, linked between them with a one-to-many and many-to-one relation.
Once a relation has data, it's no more a relation !
There is even a better way to create a Map along with initialization:
Map<String, String> rightHereMap = new HashMap<String, String>()
{
{
put("key1", "value1");
put("key2", "value2");
}
};
For more options take a look here How can I initialise a static Map?
All good answers from others. Here are two ways you can solve this:
Directly from the code where you will have to programmatically control the dimensions of the imageview
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "xyz", for: indexPath)
...
cell.imageView!.image = UIImage(named: "xyz") // if retrieving the image from the assets folder
return cell
}
From the story board, where you can use the attribute inspector & size inspector in the utility pane to adjust positioning, add constraints and specify dimensions
In the storyboard, add an imageView object in to the cell's content view with your desired dimensions and add a tag to the view(imageView) in the attribute inspector. Then do the following in your viewController
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "xyz", for: indexPath)
...
let pictureView = cell.viewWithTag(119) as! UIImageView //let's assume the tag is set to 119
pictureView.image = UIImage(named: "xyz") // if retrieving the image from the assets folder
return cell
}
You can only select columns that are in the group or used in an aggregate function. You can use a join to get this working
select s1.*
from sensorTable s1
inner join
(
SELECT sensorID, max(timestamp) as mts
FROM sensorTable
GROUP BY sensorID
) s2 on s2.sensorID = s1.sensorID and s1.timestamp = s2.mts
If the map is to contain only entries that are known at compile time and the keys to the map are integers, then you do not need to use a map at all.
char get_value(int key)
{
switch (key)
{
case 1:
return 'a';
case 2:
return 'b';
case 3:
return 'c';
default:
// Do whatever is appropriate when the key is not valid
}
}
static class Constants
{
public const int MIN_LENGTH = 5;
public const int MIN_WIDTH = 5;
public const int MIN_HEIGHT = 6;
}
// elsewhere
public CBox()
{
length = Constants.MIN_LENGTH;
width = Constants.MIN_WIDTH;
height = Constants.MIN_HEIGHT;
}
It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src
and the package file under $GOPATH/pkg/<architecture>
, for example: $GOPATH/pkg/windows_amd64
.
Remove the comma?
select /*+USE_HASH( a b ) */ to_char(date, 'MM/DD/YYYY HH24:MI:SS') as LABEL,
ltrim(rtrim(substr(oled, 9, 16))) as VALUE
from rrfh a, rrf b
where ltrim(rtrim(substr(oled, 1, 9))) = 'stata kish'
and a.xyz = b.xyz
Have a look at FROM
SELECTING from multiple tables You can include multiple tables in the FROM clause by listing the tables with a comma in between each table name
If valuationId
and user
are JavaScript variables, and the source code is plain static HTML, not generated by any means, you should try:
<a href=# onclick="return ReAssign(valuationId,user)">Re-Assign</a>
If they are generated from PHP, and they contain string values, use the escaped quoting around each variables like this:
<?php
echo '<a href=# onclick="return ReAssign(\'' + $valuationId + '\',\'' + $user + '\')">Re-Assign</a>';
?>
The logic is similar to the updated code in the question, which generates code using JavaScript (maybe using jQuery?): don't forget to apply the escaped quotes to each variable:
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td><a href=# onclick="return ReAssign(\'' + valuationId + '\',\'' + user + '\')">Re-Assign</a> </td> </tr>');
The moral of the story is
'someString(\''+'otherString'+','+'yetAnotherString'+'\')'
Will get evaluated as:
someString('otherString,yetAnotherString');
Whereas you would need:
someString('otherString','yetAnotherString');
Each answer here has parts of the total solution. Here's the complete solution that I used to get it to work inside of components deeper than where Route was used:
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
^ You need that second line to import function and to export component at bottom of page.
render() {
return (
...
<div onClick={() => this.props.history.goBack()}>GO BACK</div>
)
}
^ Required the arrow function vs simply onClick={this.props.history.goBack()}
export default withRouter(MyPage)
^ wrap your component's name with 'withRouter()'
Instead of ng-options="product as product.label for product in products">
in the select element, you can even use this:
<option ng-repeat="product in products" value="{{product.label}}">{{product.label}}
which works just fine as well.
If we want to copy an object in Java, there are two possibilities that we need to consider: a shallow copy and a deep copy.
The shallow copy is the approach when we only copy field values. Therefore, the copy might be dependent on the original object. In the deep copy approach, we make sure that all the objects in the tree are deeply copied, so the copy is not dependent on any earlier existing object that might ever change.
This question is the perfect definition for the application of the deep copy approach.
First, if you have a simple HashMap<Integer, List<T>>
map then we just create a workaround like this. Creating a new instance of the List<T>
.
public static <T> HashMap<Integer, List<T>> deepCopyWorkAround(HashMap<Integer, List<T>> original)
{
HashMap<Integer, List<T>> copy = new HashMap<>();
for (Map.Entry<Integer, List<T>> entry : original.entrySet()) {
copy.put(entry.getKey(), new ArrayList<>(entry.getValue()));
}
return copy;
}
This one uses Stream.collect()
method to create the clone map, but uses the same idea as the previous method.
public static <T> Map<Integer, List<T>> deepCopyStreamWorkAround(Map<Integer, List<T>> original)
{
return original
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, valueMapper -> new ArrayList<>(valueMapper.getValue())));
}
But, if the instances inside T
are also mutable objects we have a big problem. In this case a real deep copy is an alternative that solves this problem. Its advantage is that at least each mutable object in the object graph is recursively copied. Since the copy is not dependent on any mutable object that was created earlier, it won’t get modified by accident like we saw with the shallow copy.
To solve that this deep copy implementations will do the work.
public class DeepClone
{
public static void main(String[] args)
{
Map<Long, Item> itemMap = Stream.of(
entry(0L, new Item(2558584)),
entry(1L, new Item(254243232)),
entry(2L, new Item(986786)),
entry(3L, new Item(672542)),
entry(4L, new Item(4846)),
entry(5L, new Item(76867467)),
entry(6L, new Item(986786)),
entry(7L, new Item(7969768)),
entry(8L, new Item(68868486)),
entry(9L, new Item(923)),
entry(10L, new Item(986786)),
entry(11L, new Item(549768)),
entry(12L, new Item(796168)),
entry(13L, new Item(868421)),
entry(14L, new Item(923)),
entry(15L, new Item(986786)),
entry(16L, new Item(549768)),
entry(17L, new Item(4846)),
entry(18L, new Item(4846)),
entry(19L, new Item(76867467)),
entry(20L, new Item(986786)),
entry(21L, new Item(7969768)),
entry(22L, new Item(923)),
entry(23L, new Item(4846)),
entry(24L, new Item(986786)),
entry(25L, new Item(549768))
).collect(entriesToMap());
Map<Long, Item> clone = DeepClone.deepClone(itemMap);
clone.remove(1L);
clone.remove(2L);
System.out.println(itemMap);
System.out.println(clone);
}
private DeepClone() {}
public static <T> T deepClone(final T input)
{
if (input == null) return null;
if (input instanceof Map<?, ?>) {
return (T) deepCloneMap((Map<?, ?>) input);
} else if (input instanceof Collection<?>) {
return (T) deepCloneCollection((Collection<?>) input);
} else if (input instanceof Object[]) {
return (T) deepCloneObjectArray((Object[]) input);
} else if (input.getClass().isArray()) {
return (T) clonePrimitiveArray((Object) input);
}
return input;
}
private static Object clonePrimitiveArray(final Object input)
{
final int length = Array.getLength(input);
final Object output = Array.newInstance(input.getClass().getComponentType(), length);
System.arraycopy(input, 0, output, 0, length);
return output;
}
private static <E> E[] deepCloneObjectArray(final E[] input)
{
final E[] clone = (E[]) Array.newInstance(input.getClass().getComponentType(), input.length);
for (int i = 0; i < input.length; i++) {
clone[i] = deepClone(input[i]);
}
return clone;
}
private static <E> Collection<E> deepCloneCollection(final Collection<E> input)
{
Collection<E> clone;
if (input instanceof LinkedList<?>) {
clone = new LinkedList<>();
} else if (input instanceof SortedSet<?>) {
clone = new TreeSet<>();
} else if (input instanceof Set) {
clone = new HashSet<>();
} else {
clone = new ArrayList<>();
}
for (E item : input) {
clone.add(deepClone(item));
}
return clone;
}
private static <K, V> Map<K, V> deepCloneMap(final Map<K, V> map)
{
Map<K, V> clone;
if (map instanceof LinkedHashMap<?, ?>) {
clone = new LinkedHashMap<>();
} else if (map instanceof TreeMap<?, ?>) {
clone = new TreeMap<>();
} else {
clone = new HashMap<>();
}
for (Map.Entry<K, V> entry : map.entrySet()) {
clone.put(deepClone(entry.getKey()), deepClone(entry.getValue()));
}
return clone;
}
}
You should bind the tap event, the click does not exist on mobile safari or in the UIWbview. You can also use this polyfill ,to avoid the 300ms delay when a link is touched.
def search(request):
if 'q' in request.GET.keys():
message = 'You submitted: %r' % request.GET['q']
else:
message = 'You submitted nothing!'
return HttpResponse(message)
you can use if ... in too.
Another way on the command line if you are using ant is to use the android.bat script (Windows) or android script (Mac). It's in $SDK_DIR/tools.
If you say,
android.bat update project --path . --target "android-8"
it will regenerate your build.xml, AndroidManifest.xml, etc.
Just a heads up as I wasted way too many hours on this. I kept getting this exception even though I was calling startForeground(..)
as the first thing in onCreate(..)
.
In the end I found that the problem was caused by using NOTIFICATION_ID = 0
. Using any other value seems to fix this.
Create a conditional function breakpoint:
In the Breakpoints window, click New to create a new breakpoint.
On the Function tab, type Reverse for Function. Type 1 for Line, type 1 for Character, and then set Language to Basic.
Click Condition and make sure that the Condition checkbox is selected. Type instr.length > 0
for Condition, make sure that the is true option is selected, and then click OK.
In the New Breakpoint dialog box, click OK.
On the Debug menu, click Start.
You're trying to assign the result of the add operation to resultArrGame, and add can either return true or false, depending on if the operation was successful or not. What you want is probably just:
resultArrGame.add(txt.Game.getText().toString());
You are not returning. Change to
this.state.data.map(function(item, i){
console.log('test');
return <li>Test</li>;
})
Here's how you do this with react-router v2.0.0
with ES6. react-router
has moved away from mixins.
import React from 'react';
export default class MyComponent extends React.Component {
navigateToPage = () => {
this.context.router.push('/my-route')
};
render() {
return (
<button onClick={this.navigateToPage}>Go!</button>
);
}
}
MyComponent.contextTypes = {
router: React.PropTypes.object.isRequired
}
To do it in a simpler way, consider below:
JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
When you approach this question as a programmer, one factor stands out: if you're using recursion, then depth-first search is simpler to implement, because you don't need to maintain an additional data structure containing the nodes yet to explore.
Here's depth-first search for a non-oriented graph if you're storing “already visited” information in the nodes:
def dfs(origin): # DFS from origin:
origin.visited = True # Mark the origin as visited
for neighbor in origin.neighbors: # Loop over the neighbors
if not neighbor.visited: dfs(neighbor) # Visit each neighbor if not already visited
If storing “already visited” information in a separate data structure:
def dfs(node, visited): # DFS from origin, with already-visited set:
visited.add(node) # Mark the origin as visited
for neighbor in node.neighbors: # Loop over the neighbors
if not neighbor in visited: # If the neighbor hasn't been visited yet,
dfs(neighbor, visited) # then visit the neighbor
dfs(origin, set())
Contrast this with breadth-first search where you need to maintain a separate data structure for the list of nodes yet to visit, no matter what.
Xcode which is part of the MacOS Developer Tools is a great IDE. There's also NetBeans and Eclipse that can be configured to build and compile C++ projects.
Clion from JetBrains, also is available now, and uses Cmake as project model.
I think this example will help you in understanding this more simply.
Path differences in Windows
Windows absolute path C:\Windows\calc.exe
Windows non absolute path (relative path) calc.exe
In the above example, the absolute path contains the full path to the file and not just the file as seen in the non absolute path. In this example, if you were in a directory that did not contain "calc.exe" you would get an error message. However, when using an absolute path you can be in any directory and the computer would know where to open the "calc.exe" file.
Path differences in Linux
Linux absolute path /home/users/c/computerhope/public_html/cgi-bin
Linux non absolute path (relative path) /public_html/cgi-bin
In these example, the absolute path contains the full path to the cgi-bin directory on that computer. How to find the absolute path of a file in Linux Since most users do not want to see the full path as their prompt, by default the prompt is relative to their personal directory as shown above. To find the full absolute path of the current directory use the pwd command.
It is a best practice to use relative file paths (if possible).
When using relative file paths, your web pages will not be bound to your current base URL. All links will work on your own computer (localhost) as well as on your current public domain and your future public domains.
For bash, store your command like this:
command="ls | grep -c '^'"
Run your command like this:
echo $command | bash
The solution is to add height:100%;
to all the parent elements of your .wrapper-div
as well. So:
html{
height: 100%;
}
body{
margin:0;
padding:0;
overflow:hidden;
height:100%;
}
#container{
width:1000px;
margin:0 auto;
height:100%;
}
This is assuming a list of YourClass
instead of Object
, as explained by amit.
You can use this bit from the Google Guava library:
Collections.sort(list, Ordering.natural()
.onResultOf(new Function<String,YourClass>() {
public String call(YourClass o) {
return o.getName();
}))
.nullsLast();
The other answers which mention Comparator
are not incorrect, since Ordering
implements Comparator
. This solution is, in my opinion, a little easier, though it may be harder if you're a beginner and not used to using libraries and/or "functional programming".
Copied shamelessly from this answer on my own question.
OK, I found it finally.
Key Event This document lists volume up as 24. The key code I was looking for is Alt-Menu and apparently it executes regardless of having the key intercepted.
Thanks to those those who took the time to reply.
It is not on PyPI and you should not be installing it via pip
. If you have matplotlib
installed, you should be able to import mpl_toolkits
directly:
$ pip install --upgrade matplotlib
...
$ python
>>> import mpl_toolkits
>>>
Whenever You merge two branches using command git merge brancha branchb
, There are two possibilities:
One branch (lets say brancha) can be reached by the other branch (lets say branchb) by following its commits history.In this case git simply fast-forward the head to point to the recent branch (in this case branchb).
2.But if the two branches have diverged at some older point then git creates a new snapshot and add a new commit that points to it. So in case there is no conflict between the branches you are merging, git smoothly creates a new commit.
Run
git log
to see the commit after you have merged two non-conflicting branches.
Now coming back to the interesting case when there are merge conflicts between the merging branches. I quote this from the page https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging
Git hasn’t automatically created a new merge commit. It has paused the process while you resolve the conflict. If you want to see which files are unmerged at any point after a merge conflict, you can run
git status
So in case there are merge conflicts, you need to resolve the conflict then add the changes you have made to the staging area using git add filename
and then commit the changes by using the command git commit
which was paused by git because of the conflict.I hope this explains your query. Also do visit the link above for a detailed understanding. In case of any query please comment below , I'll be happy to help.
Thanks Cody heres the c# for ref:
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
DataGridView.HitTestInfo hit = dgv_track.HitTest(e.X, e.Y);
if (hit.Type == DataGridViewHitTestType.None)
{
dgv_track.ClearSelection();
dgv_track.CurrentCell = null;
}
}
Uh, WHERE mydate<='2008-11-25'
is the way to do it. That should work.
Do you get an error message? Are you using an ancient version of MySQL?
Edit: The following works fine for me on MySQL 5.x
create temporary table foo(d datetime);
insert into foo(d) VALUES ('2000-01-01');
insert into foo(d) VALUES ('2001-01-01');
select * from foo where d <= '2000-06-01';
Main problem with "This application is modifying the autolayout engine from a background thread" is that it seem to be logged a long time after the actual problem occurs, this can make it very hard to troubleshoot.
I managed to solve the issue by creating three symbolic breakpoints.
Debug > Breakpoints > Create Symbolic Breakpoint...
Breakpoint 1:
Symbol: -[UIView setNeedsLayout]
Condition: !(BOOL)[NSThread isMainThread]
Breakpoint 2:
Symbol: -[UIView layoutIfNeeded]
Condition: !(BOOL)[NSThread isMainThread]
Breakpoint 3:
Symbol: -[UIView updateConstraintsIfNeeded]
Condition: !(BOOL)[NSThread isMainThread]
With these breakpoints, you can easily get a break on the actual line where you incorrectly call UI methods on non-main thread.
Try the below code snippet
<!doctype html>
<html>
<head>
<title>Audio</title>
</head>
<body>
<script>
function play() {
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="http://dev.interactive-creation-works.net/1/1.ogg"></audio>
</body>
</html>
Workaround....
In VS 2015 Professional (and probably other versions). Go to Tools / Options / Environment / Fonts and Colours. In the "Show Settings For" drop-down, select "CodeLens" Choose the smallest font you can find e.g. Calibri 6. Change the foreground colour to your editor foreground colour (say "White") Click OK.
I'm a Scala beginner and I honestly don't see a problem with that type signature. The parameter is the function to map and the implicit parameter the builder to return the correct collection. Clear and readable.
The whole thing's quite elegant, actually. The builder type parameters let the compiler choose the correct return type while the implicit parameter mechanism hides this extra parameter from the class user. I tried this:
Map(1 -> "a", 2 -> "b").map((t) => (t._2) -> (t._1)) // returns Map("a" -> 1, "b" -> 2)
Map(1 -> "a", 2 -> "b").map((t) => t._2) // returns List("a", "b")
That's polymorphism done right.
Now, granted, it's not a mainstream paradigm and it will scare away many. But, it will also attract many who value its expressiveness and elegance.
None of those worked for me in Chrome 42...
Instead my directive now uses this link
function (base64
made it work):
link: function(scope, element, attrs) {
var downloadFile = function downloadFile() {
var filename = scope.getFilename();
var link = angular.element('<a/>');
link.attr({
href: 'data:attachment/csv;base64,' + encodeURI($window.btoa(scope.csv)),
target: '_blank',
download: filename
})[0].click();
$timeout(function(){
link.remove();
}, 50);
};
element.bind('click', function(e) {
scope.buildCSV().then(function(csv) {
downloadFile();
});
scope.$apply();
});
}
Swift 4 You cannot compare Any to nil.Because an optional can be nil and hence it always succeeds to true. The only way is to cast it to your desired object and compare it to nil.
if (someone as? String) != nil
{
//your code`enter code here`
}
Based on what Warlock wrote, I found that the virtual path root is needed if you aren't hosted at the root of your web. (This works for MVC Web API controllers)
String baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority)
+ Configuration.VirtualPathRoot;
This solution for Swift 4.1
textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])
After looking at sp_who, Oracle does not have that ability per se. Oracle has at least 8 processes running which run the db. Like RMON etc.
You can ask the DB which queries are running as that just a table query. Look at the V$ tables.
Quick Example:
SELECT sid,
opname,
sofar,
totalwork,
units,
elapsed_seconds,
time_remaining
FROM v$session_longops
WHERE sofar != totalwork;
Just for someone who have the same problem I did. If you just want to make some insert just once you can do something like this.
Lets suppose you have a table with two columns
ID Identity (1,1) | Name Varchar
and want to insert a row with the ID = 4. So you Reseed it to 3 so the next one is 4
DBCC CHECKIDENT([YourTable], RESEED, 3)
Make the Insert
INSERT INTO [YourTable]
( Name )
VALUES ( 'Client' )
And get your seed back to the highest ID, lets suppose is 15
DBCC CHECKIDENT([YourTable], RESEED, 15)
Done!
From the jQuery documentation:
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().
Can this be fast solution?
int byte_to_be_reversed =
((byte_to_be_reversed>>7)&0x01)|((byte_to_be_reversed>>5)&0x02)|
((byte_to_be_reversed>>3)&0x04)|((byte_to_be_reversed>>1)&0x08)|
((byte_to_be_reversed<<7)&0x80)|((byte_to_be_reversed<<5)&0x40)|
((byte_to_be_reversed<<3)&0x20)|((byte_to_be_reversed<<1)&0x10);
Gets rid of the hustle of using a for loop! but experts please tell me if this is efficient and faster?
What you want to see is the list of outgoing commits. You can do this using
git log master..branchName
or
git log master..branchName --oneline
Where I assume that "branchName" was created as a tracking branch of "master".
Similarly, to see the incoming changes you can use:
git log branchName..master
This will give you the difference between two dates, in milliseconds
var diff = Math.abs(date1 - date2);
In your example, it'd be
var diff = Math.abs(new Date() - compareDate);
You need to make sure that compareDate
is a valid Date
object.
Something like this will probably work for you
var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));
i.e. turning "2011-02-07 15:13:06"
into new Date('2011/02/07 15:13:06')
, which is a format the Date
constructor can comprehend.
IF,
Then,
It is highly recommended that you install xampp 1.7.0 . Download Link
Note: This is not a solution to the above problem, but a FIX which would allow you to continue with your development.
A more pythonic way, without using set is as follows:
lst = [1, 2, 3, 4]
lst.append(3) if 3 not in lst else lst
You can do a simple wildcard mach without RegEx using a Visual Basic function called LikeString.
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
if (Operators.LikeString("This is just a test", "*just*", CompareMethod.Text))
{
Console.WriteLine("This matched!");
}
If you use CompareMethod.Text
it will compare case-insensitive. For case-sensitive comparison, you can use CompareMethod.Binary
.
More info here: http://www.henrikbrinch.dk/Blog/2012/02/14/Wildcard-matching-in-C
This is my code .This works for me
componentDidMount(){
axios.get('http://localhost:5000/supplier').then(
response => {
console.log(response)
this.setState({suppliers:response.data.data})
}
)
.catch(error => {
console.log(error)
})
}
componentDidUpdate(){
this.componentDidMount();
}
window.location.reload(); I think this thing is not good for react js
a <div>
can be focused if it has a tabindex
attribute. (the value can be set to -1)
For example:
$("#focus_point").attr("tabindex",-1).focus();
In addition, consider setting outline: none !important;
so it displayed without a focus rectangle.
var element = $("#focus_point");
element.css('outline', 'none !important')
.attr("tabindex", -1)
.focus();
As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:
Directory.CreateDirectory(Path.GetDirectoryName(filePath))
An app is available that demonstrates a listview that combines both swiping-to-delete and dragging to reorder items. The code is based on Chet Haase's code for swiping-to-delete and Daniel Olshansky's code for dragging-to-reorder.
Chet's code deletes an item immediately. I improved on this by making it function more like Gmail where swiping reveals a bottom view that indicates that the item is deleted but provides an Undo button where the user has the possibility to undo the deletion. Chet's code also has a bug in it. If you have less items in the listview than the height of the listview is and you delete the last item, the last item appears to not be deleted. This was fixed in my code.
Daniel's code requires pressing long on an item. Many users find this unintuitive as it tends to be a hidden function. Instead, I modified the code to allow for a "Move" button. You simply press on the button and drag the item. This is more in line with the way the Google News app works when you reorder news topics.
The source code along with a demo app is available at: https://github.com/JohannBlake/ListViewOrderAndSwipe
Chet and Daniel are both from Google.
Chet's video on deleting items can be viewed at: https://www.youtube.com/watch?v=YCHNAi9kJI4
Daniel's video on reordering items can be viewed at: https://www.youtube.com/watch?v=_BZIvjMgH-Q
A considerable amount of work went into gluing all this together to provide a seemless UI experience, so I'd appreciate a Like or Up Vote. Please also star the project in Github.
This is a DevExpress
specific answer based on the top-voted answer by Gregor S.
(currently it has 128 votes).
This means we can keep the styling consistent across the entire application:
Unfortunately, the original answer doesn't work with a ComboBoxEdit
from DevExpress without some modifications.
First, the XAML for the ComboBoxEdit
:
<dxe:ComboBoxEdit ItemsSource="{Binding Source={xamlExtensions:XamlExtensionEnumDropdown {x:myEnum:EnumFilter}}}"
SelectedItem="{Binding BrokerOrderBookingFilterSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
DisplayMember="Description"
MinWidth="144" Margin="5"
HorizontalAlignment="Left"
IsTextEditable="False"
ValidateOnTextInput="False"
AutoComplete="False"
IncrementalFiltering="True"
FilterCondition="Like"
ImmediatePopup="True"/>
Needsless to say, you will need to point xamlExtensions
at the namespace that contains the XAML extension class (which is defined below):
xmlns:xamlExtensions="clr-namespace:XamlExtensions"
And we have to point myEnum
at the namespace that contains the enum:
xmlns:myEnum="clr-namespace:MyNamespace"
Then, the enum:
namespace MyNamespace
{
public enum EnumFilter
{
[Description("Free as a bird")]
Free = 0,
[Description("I'm Somewhat Busy")]
SomewhatBusy = 1,
[Description("I'm Really Busy")]
ReallyBusy = 2
}
}
The problem in with the XAML is that we can't use SelectedItemValue
, as this throws an error as the setter is unaccessable (bit of an oversight on your part, DevExpress
). So we have to modify our ViewModel
to obtain the value directly from the object:
private EnumFilter _filterSelected = EnumFilter.All;
public object FilterSelected
{
get
{
return (EnumFilter)_filterSelected;
}
set
{
var x = (XamlExtensionEnumDropdown.EnumerationMember)value;
if (x != null)
{
_filterSelected = (EnumFilter)x.Value;
}
OnPropertyChanged("FilterSelected");
}
}
For completeness, here is the XAML extension from the original answer (slightly renamed):
namespace XamlExtensions
{
/// <summary>
/// Intent: XAML markup extension to add support for enums into any dropdown box, see http://bit.ly/1g70oJy. We can name the items in the
/// dropdown box by using the [Description] attribute on the enum values.
/// </summary>
public class XamlExtensionEnumDropdown : MarkupExtension
{
private Type _enumType;
public XamlExtensionEnumDropdown(Type enumType)
{
if (enumType == null)
{
throw new ArgumentNullException("enumType");
}
EnumType = enumType;
}
public Type EnumType
{
get { return _enumType; }
private set
{
if (_enumType == value)
{
return;
}
var enumType = Nullable.GetUnderlyingType(value) ?? value;
if (enumType.IsEnum == false)
{
throw new ArgumentException("Type must be an Enum.");
}
_enumType = value;
}
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
var enumValues = Enum.GetValues(EnumType);
return (
from object enumValue in enumValues
select new EnumerationMember
{
Value = enumValue,
Description = GetDescription(enumValue)
}).ToArray();
}
private string GetDescription(object enumValue)
{
var descriptionAttribute = EnumType
.GetField(enumValue.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false)
.FirstOrDefault() as DescriptionAttribute;
return descriptionAttribute != null
? descriptionAttribute.Description
: enumValue.ToString();
}
#region Nested type: EnumerationMember
public class EnumerationMember
{
public string Description { get; set; }
public object Value { get; set; }
}
#endregion
}
}
Disclaimer: I have no affiliation with DevExpress. Telerik is also a great library.
I use the following code:
namespace Core
{
typedef std::wstring String;
void SplitString(const Core::String& input, const Core::String& splitter, std::list<Core::String>& output)
{
if (splitter.empty())
{
throw std::invalid_argument(); // for example
}
std::list<Core::String> lines;
Core::String::size_type offset = 0;
for (;;)
{
Core::String::size_type splitterPos = input.find(splitter, offset);
if (splitterPos != Core::String::npos)
{
lines.push_back(input.substr(offset, splitterPos - offset));
offset = splitterPos + splitter.size();
}
else
{
lines.push_back(input.substr(offset));
break;
}
}
lines.swap(output);
}
}
// gtest:
class SplitStringTest: public testing::Test
{
};
TEST_F(SplitStringTest, EmptyStringAndSplitter)
{
std::list<Core::String> result;
ASSERT_ANY_THROW(Core::SplitString(Core::String(), Core::String(), result));
}
TEST_F(SplitStringTest, NonEmptyStringAndEmptySplitter)
{
std::list<Core::String> result;
ASSERT_ANY_THROW(Core::SplitString(L"xy", Core::String(), result));
}
TEST_F(SplitStringTest, EmptyStringAndNonEmptySplitter)
{
std::list<Core::String> result;
Core::SplitString(Core::String(), Core::String(L","), result);
ASSERT_EQ(1, result.size());
ASSERT_EQ(Core::String(), *result.begin());
}
TEST_F(SplitStringTest, OneCharSplitter)
{
std::list<Core::String> result;
Core::SplitString(L"x,y", L",", result);
ASSERT_EQ(2, result.size());
ASSERT_EQ(L"x", *result.begin());
ASSERT_EQ(L"y", *result.rbegin());
Core::SplitString(L",xy", L",", result);
ASSERT_EQ(2, result.size());
ASSERT_EQ(Core::String(), *result.begin());
ASSERT_EQ(L"xy", *result.rbegin());
Core::SplitString(L"xy,", L",", result);
ASSERT_EQ(2, result.size());
ASSERT_EQ(L"xy", *result.begin());
ASSERT_EQ(Core::String(), *result.rbegin());
}
TEST_F(SplitStringTest, TwoCharsSplitter)
{
std::list<Core::String> result;
Core::SplitString(L"x,.y,z", L",.", result);
ASSERT_EQ(2, result.size());
ASSERT_EQ(L"x", *result.begin());
ASSERT_EQ(L"y,z", *result.rbegin());
Core::SplitString(L"x,,y,z", L",,", result);
ASSERT_EQ(2, result.size());
ASSERT_EQ(L"x", *result.begin());
ASSERT_EQ(L"y,z", *result.rbegin());
}
TEST_F(SplitStringTest, RecursiveSplitter)
{
std::list<Core::String> result;
Core::SplitString(L",,,", L",,", result);
ASSERT_EQ(2, result.size());
ASSERT_EQ(Core::String(), *result.begin());
ASSERT_EQ(L",", *result.rbegin());
Core::SplitString(L",.,.,", L",.,", result);
ASSERT_EQ(2, result.size());
ASSERT_EQ(Core::String(), *result.begin());
ASSERT_EQ(L".,", *result.rbegin());
Core::SplitString(L"x,.,.,y", L",.,", result);
ASSERT_EQ(2, result.size());
ASSERT_EQ(L"x", *result.begin());
ASSERT_EQ(L".,y", *result.rbegin());
Core::SplitString(L",.,,.,", L",.,", result);
ASSERT_EQ(3, result.size());
ASSERT_EQ(Core::String(), *result.begin());
ASSERT_EQ(Core::String(), *(++result.begin()));
ASSERT_EQ(Core::String(), *result.rbegin());
}
TEST_F(SplitStringTest, NullTerminators)
{
std::list<Core::String> result;
Core::SplitString(L"xy", Core::String(L"\0", 1), result);
ASSERT_EQ(1, result.size());
ASSERT_EQ(L"xy", *result.begin());
Core::SplitString(Core::String(L"x\0y", 3), Core::String(L"\0", 1), result);
ASSERT_EQ(2, result.size());
ASSERT_EQ(L"x", *result.begin());
ASSERT_EQ(L"y", *result.rbegin());
}
It's very simple.
You create a css property to this image.
img { transition: all 0.3s ease-in-out 0s; }
You add an animation like that:
img:hover
{
cursor: default;
transform: rotate(360deg);
transition: all 0.3s ease-in-out 0s;
}
In my case I substitute it with utf8_general_ci
with sed like this:
sed -i 's/utf8_0900_ai_ci/utf8_general_ci/g' MY_DB.sql
sed -i 's/utf8mb4_unicode_520_ci/utf8_general_ci/g' MY_DB.sql
After that, I can import it without any issue.
Each elapsed event will fire in the same thread unless a previous Elapsed is still running.
So it handles the collision for you
try putting this in a console
static void Main(string[] args)
{
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
var timer = new Timer(1000);
timer.Elapsed += timer_Elapsed;
timer.Start();
Console.ReadLine();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Thread.Sleep(2000);
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
you will get something like this
10
6
12
6
12
where 10 is the calling thread and 6 and 12 are firing from the bg elapsed event. If you remove the Thread.Sleep(2000); you will get something like this
10
6
6
6
6
Since there are no collisions.
But this still leaves u with a problem. if u are firing the event every 5 seconds and it takes 10 seconds to edit u need some locking to skip some edits.
PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn
which will show the process names (but must be run under an administrator account).
Having said that, I would expect the find "8080"
to find it...
Another thing to do is just visit http://localhost:8080
- on that port, chances are it's a web server of some description.
The best solution in my opinion is to encapsulate the InputStream in a JSONTokener object. Something like this:
JSONObject jsonObject = new JSONObject(new JSONTokener(inputStream));
Local temporary tables: if you create local temporary tables and then open another connection and try the query , you will get the following error.
the temporary tables are only accessible within the session that created them.
Global temporary tables: Sometimes, you may want to create a temporary table that is accessible other connections. In this case, you can use global temporary tables.
Global temporary tables are only destroyed when all the sessions referring to it are closed.
try this
SELECT group_name, employees, surveys, COUNT( surveys ) AS test1,
concat(round(( surveys/employees * 100 ),2),'%') AS percentage
FROM a_test
GROUP BY employees
One Additional point:
When you are converting from tsql
to plsql
you have to worry about no_data_found
exception
DECLARE
v_var NUMBER;
BEGIN
SELECT clmn INTO v_var FROM tbl;
Exception when no_data_found then v_var := null; --what ever handle the exception.
END;
In tsql
if no data found
then the variable will be null
but no exception
Try this
final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
I just wanted to mention that one can get the detailed GC log with the
-XX:+PrintGCDetails
parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.
Also -Xloggc:gc.log
seems to generate the same output like -verbose:gc
but you can specify an output file in the first.
Example usage:
java -Xloggc:./memory.log -XX:+PrintGCDetails Memory
To visualize the data better you can try gcviewer (a more recent version can be found on github).
Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!
Please refer to the following method. It takes your date String as argument1, you need to specify the existing format of the date as argument2, and the result (expected) format as argument 3.
Refer to this link to understand various formats: Available Date Formats
public static String formatDateFromOnetoAnother(String date,String givenformat,String resultformat) {
String result = "";
SimpleDateFormat sdf;
SimpleDateFormat sdf1;
try {
sdf = new SimpleDateFormat(givenformat);
sdf1 = new SimpleDateFormat(resultformat);
result = sdf1.format(sdf.parse(date));
}
catch(Exception e) {
e.printStackTrace();
return "";
}
finally {
sdf=null;
sdf1=null;
}
return result;
}
This is a good approach to show animation in and out using jQuery
$(document).ready(function() {
// show the alert
$(".alert").first().hide().slideDown(500).delay(4000).slideUp(500, function () {
$(this).remove();
});
});
The below annotated code would set "value" to "name"
@RequestMapping("/testing")
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
request.getSession().setAttribute("name", "value");
return "testJsp";
}
}
To access the same in JSP use
${sessionScope.name}
.
For the @ModelAttribute
see this link
Seaborn takes care of a lot of the manual work and automatically plots a gradient at the side of the chart etc.
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, linewidth=0.5)
plt.show()
Or, you can even plot upper / lower left / right triangles of square matrices, for example a correlation matrix which is square and is symmetric, so plotting all values would be redundant anyway.
corr = np.corrcoef(np.random.randn(10, 200))
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True, cmap="YlGnBu")
plt.show()
PHP Mess Detector is awesome and fast.
An easy example would be something like:
writer = csv.writer(open("filename.csv", "wb")) String[] entries = "first#second#third".split("#"); writer.writerows(entries) writer.close()
You do not need to do with web.config You can use short property during catch value of the passing list For example declare a model like
public class BookModel
{
public decimal id { get; set; } // 1
public string BN { get; set; } // 2 Book Name
public string BC { get; set; } // 3 Bar Code Number
public string BE { get; set; } // 4 Edition Name
public string BAL { get; set; } // 5 Academic Level
public string BCAT { get; set; } // 6 Category
}
here i use short proporties like BC =barcode BE=book edition and so on
When I pass a little complex DOM query to $._data like this: $._data($('#outerWrap .innerWrap ul li:last a'), 'events')
it throws undefined in the browser console.
So I had to use $._data on the parent div: $._data($('#outerWrap')[0], 'events')
to see the events for the a tags. Here is a JSFiddle for the same: http://jsfiddle.net/giri_jeedigunta/MLcpT/4/
I'm using similar approach as @dtheodot but using angular promise instead of passing callbacks
app.service('myService', function($q) {
var self = this,
defer = $q.defer();
this.foo = 0;
this.observeFoo = function() {
return defer.promise;
}
this.setFoo = function(foo) {
self.foo = foo;
defer.notify(self.foo);
}
})
Then wherever just use myService.setFoo(foo)
method to update foo
on service. In your controller you can use it as:
myService.observeFoo().then(null, null, function(foo){
$scope.foo = foo;
})
First two arguments of then
are success and error callbacks, third one is notify callback.
Here is a shorter solution by AbacusUtil
Stream.of(input).toMap(e -> e.getKey().substring(subLength),
e -> AttributeType.GetByName(e.getValue()));
Try this..
select starttime,endtime, case
when DATEDIFF(minute,starttime,endtime) < 60 then DATEDIFF(minute,starttime,endtime)
when DATEDIFF(minute,starttime,endtime) >= 60
then '60,'+ cast( (cast(DATEDIFF(minute,starttime,endtime) as int )-60) as nvarchar(50) )
end from TestTable123416
All You need is DateDiff..
well you could do this, but it's not esp general
'I pity the $fool'.replace('$fool', 'fool')
You could easily write a function that does this intelligently if you really needed to
You can also use split
and join
:
"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games
You can use the EXACT
Function for exact string comparisons.
=IF(EXACT(A1, "ENG"), 1, 0)
Another one is to use the -F option but pass it regex to print the text between left and or right parenthesis ()
.
The file content:
528(smbw)
529(smbt)
530(smbn)
10115(smbs)
The command:
awk -F"[()]" '{print $2}' filename
result:
smbw
smbt
smbn
smbs
Using awk to just print the text between []
:
Use awk -F'[][]'
but awk -F'[[]]'
will not work.
http://stanlo45.blogspot.com/2020/06/awk-multiple-field-separators.html
As of Powershell v3, PSsessions allow for any native cmdlet to be run on a remote machine
$session = New-PSsession -Computername "YourServerName"
Invoke-Command -Session $Session -ScriptBlock {Restart-Service "YourServiceName"}
Remove-PSSession $Session
See here for more information
String cleanString = dirtyString.strip() ; // Call new `String::string` method.
String::strip…
The old String::trim
method has a strange definition of whitespace.
As discussed here, Java 11 adds new strip…
methods to the String
class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace
.
Example code.
String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");
Or you can strip just the leading or just the trailing whitespace.
You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip
:
Since it seems impossible to do just with symbol versioning hacks, let's go one step further and compile glibc ourselves.
This setup might work and is quick as it does not recompile the whole GCC toolchain, just glibc.
But it is not reliable as it uses host C runtime objects such as crt1.o
, crti.o
, and crtn.o
provided by glibc. This is mentioned at: https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location Those objects do early setup that glibc relies on, so I wouldn't be surprised if things crashed in wonderful and awesomely subtle ways.
For a more reliable setup, see Setup 2 below.
Build glibc and install locally:
export glibc_install="$(pwd)/glibc/build/install"
git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
mkdir build
cd build
../configure --prefix "$glibc_install"
make -j `nproc`
make install -j `nproc`
test_glibc.c
#define _GNU_SOURCE
#include <assert.h>
#include <gnu/libc-version.h>
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>
atomic_int acnt;
int cnt;
int f(void* thr_data) {
for(int n = 0; n < 1000; ++n) {
++cnt;
++acnt;
}
return 0;
}
int main(int argc, char **argv) {
/* Basic library version check. */
printf("gnu_get_libc_version() = %s\n", gnu_get_libc_version());
/* Exercise thrd_create from -pthread,
* which is not present in glibc 2.27 in Ubuntu 18.04.
* https://stackoverflow.com/questions/56810/how-do-i-start-threads-in-plain-c/52453291#52453291 */
thrd_t thr[10];
for(int n = 0; n < 10; ++n)
thrd_create(&thr[n], f, NULL);
for(int n = 0; n < 10; ++n)
thrd_join(thr[n], NULL);
printf("The atomic counter is %u\n", acnt);
printf("The non-atomic counter is %u\n", cnt);
}
Compile and run with test_glibc.sh
:
#!/usr/bin/env bash
set -eux
gcc \
-L "${glibc_install}/lib" \
-I "${glibc_install}/include" \
-Wl,--rpath="${glibc_install}/lib" \
-Wl,--dynamic-linker="${glibc_install}/lib/ld-linux-x86-64.so.2" \
-std=c11 \
-o test_glibc.out \
-v \
test_glibc.c \
-pthread \
;
ldd ./test_glibc.out
./test_glibc.out
The program outputs the expected:
gnu_get_libc_version() = 2.28
The atomic counter is 10000
The non-atomic counter is 8674
Command adapted from https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location but --sysroot
made it fail with:
cannot find /home/ciro/glibc/build/install/lib/libc.so.6 inside /home/ciro/glibc/build/install
so I removed it.
ldd
output confirms that the ldd
and libraries that we've just built are actually being used as expected:
+ ldd test_glibc.out
linux-vdso.so.1 (0x00007ffe4bfd3000)
libpthread.so.0 => /home/ciro/glibc/build/install/lib/libpthread.so.0 (0x00007fc12ed92000)
libc.so.6 => /home/ciro/glibc/build/install/lib/libc.so.6 (0x00007fc12e9dc000)
/home/ciro/glibc/build/install/lib/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007fc12f1b3000)
The gcc
compilation debug output shows that my host runtime objects were used, which is bad as mentioned previously, but I don't know how to work around it, e.g. it contains:
COLLECT_GCC_OPTIONS=/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crt1.o
Now let's modify glibc with:
diff --git a/nptl/thrd_create.c b/nptl/thrd_create.c
index 113ba0d93e..b00f088abb 100644
--- a/nptl/thrd_create.c
+++ b/nptl/thrd_create.c
@@ -16,11 +16,14 @@
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
+#include <stdio.h>
+
#include "thrd_priv.h"
int
thrd_create (thrd_t *thr, thrd_start_t func, void *arg)
{
+ puts("hacked");
_Static_assert (sizeof (thr) == sizeof (pthread_t),
"sizeof (thr) != sizeof (pthread_t)");
Then recompile and re-install glibc, and recompile and re-run our program:
cd glibc/build
make -j `nproc`
make -j `nproc` install
./test_glibc.sh
and we see hacked
printed a few times as expected.
This further confirms that we actually used the glibc that we compiled and not the host one.
Tested on Ubuntu 18.04.
This is an alternative to setup 1, and it is the most correct setup I've achieved far: everything is correct as far as I can observe, including the C runtime objects such as crt1.o
, crti.o
, and crtn.o
.
In this setup, we will compile a full dedicated GCC toolchain that uses the glibc that we want.
The only downside to this method is that the build will take longer. But I wouldn't risk a production setup with anything less.
crosstool-NG is a set of scripts that downloads and compiles everything from source for us, including GCC, glibc and binutils.
Yes the GCC build system is so bad that we need a separate project for that.
This setup is only not perfect because crosstool-NG does not support building the executables without extra -Wl
flags, which feels weird since we've built GCC itself. But everything seems to work, so this is only an inconvenience.
Get crosstool-NG and configure it:
git clone https://github.com/crosstool-ng/crosstool-ng
cd crosstool-ng
git checkout a6580b8e8b55345a5a342b5bd96e42c83e640ac5
export CT_PREFIX="$(pwd)/.build/install"
export PATH="/usr/lib/ccache:${PATH}"
./bootstrap
./configure --enable-local
make -j `nproc`
./ct-ng x86_64-unknown-linux-gnu
./ct-ng menuconfig
The only mandatory option that I can see, is making it match your host kernel version to use the correct kernel headers. Find your host kernel version with:
uname -a
which shows me:
4.15.0-34-generic
so in menuconfig
I do:
Operating System
Version of linux
so I select:
4.14.71
which is the first equal or older version. It has to be older since the kernel is backwards compatible.
Now you can build with:
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`
and now wait for about thirty minutes to two hours for compilation.
The .config
that we generated with ./ct-ng x86_64-unknown-linux-gnu
has:
CT_GLIBC_V_2_27=y
To change that, in menuconfig
do:
C-library
Version of glibc
save the .config
, and continue with the build.
Or, if you want to use your own glibc source, e.g. to use glibc from the latest git, proceed like this:
Paths and misc options
Try features marked as EXPERIMENTAL
: set to trueC-library
Source of glibc
Custom location
: say yesCustom location
Custom source location
: point to a directory containing your glibc sourcewhere glibc was cloned as:
git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
Once you have built he toolchain that you want, test it out with:
#!/usr/bin/env bash
set -eux
install_dir="${CT_PREFIX}/x86_64-unknown-linux-gnu"
PATH="${PATH}:${install_dir}/bin" \
x86_64-unknown-linux-gnu-gcc \
-Wl,--dynamic-linker="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib/ld-linux-x86-64.so.2" \
-Wl,--rpath="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib" \
-v \
-o test_glibc.out \
test_glibc.c \
-pthread \
;
ldd test_glibc.out
./test_glibc.out
Everything seems to work as in Setup 1, except that now the correct runtime objects were used:
COLLECT_GCC_OPTIONS=/home/ciro/crosstool-ng/.build/install/x86_64-unknown-linux-gnu/bin/../x86_64-unknown-linux-gnu/sysroot/usr/lib/../lib64/crt1.o
It does not seem possible with crosstool-NG, as explained below.
If you just re-build;
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`
then your changes to the custom glibc source location are taken into account, but it builds everything from scratch, making it unusable for iterative development.
If we do:
./ct-ng list-steps
it gives a nice overview of the build steps:
Available build steps, in order:
- companion_tools_for_build
- companion_libs_for_build
- binutils_for_build
- companion_tools_for_host
- companion_libs_for_host
- binutils_for_host
- cc_core_pass_1
- kernel_headers
- libc_start_files
- cc_core_pass_2
- libc
- cc_for_build
- cc_for_host
- libc_post_cc
- companion_libs_for_target
- binutils_for_target
- debug
- test_suite
- finish
Use "<step>" as action to execute only that step.
Use "+<step>" as action to execute up to that step.
Use "<step>+" as action to execute from that step onward.
therefore, we see that there are glibc steps intertwined with several GCC steps, most notably libc_start_files
comes before cc_core_pass_2
, which is likely the most expensive step together with cc_core_pass_1
.
In order to build just one step, you must first set the "Save intermediate steps" in .config
option for the intial build:
Paths and misc options
Debug crosstool-NG
Save intermediate steps
and then you can try:
env -u LD_LIBRARY_PATH time ./ct-ng libc+ -j`nproc`
but unfortunately, the +
required as mentioned at: https://github.com/crosstool-ng/crosstool-ng/issues/1033#issuecomment-424877536
Note however that restarting at an intermediate step resets the installation directory to the state it had during that step. I.e., you will have a rebuilt libc - but no final compiler built with this libc (and hence, no compiler libraries like libstdc++ either).
and basically still makes the rebuild too slow to be feasible for development, and I don't see how to overcome this without patching crosstool-NG.
Furthermore, starting from the libc
step didn't seem to copy over the source again from Custom source location
, further making this method unusable.
A bonus if you're also interested in the C++ standard library: How to edit and re-build the GCC libstdc++ C++ standard library source?
For simplicity, why not create the backup table from the select statement?
CREATE TABLE t1_backup AS SELECT a, b FROM t1;
DROP TABLE t1;
ALTER TABLE t1_backup RENAME TO t1;